Problem with Update-BTNotification (Burnt Toast for Powershell) - windows

I'm trying to make a small PowerShell program to display a toast notification that will show me in real-time how a copy job is doing. For the moment I haven't coded origin/copy size-compare program, so it's supposed to go up of 1% every second.
$image = New-BTImage -Source "D:\Pictures\Profile image.png" -Crop Circle
$binding = #{
text1 = "Downloading your files..."
text2 = "Your files are being downloaded so they can be available offline."
image = $image
value = 0
}
$progress = New-BTProgressBar -Status "Downloading..." -Value $binding['value'] -Title "Download" -Verbose
New-BurntToastNotification -Text $binding['text1'], $binding['text2'] -AppLogo $binding['image'] -ProgressBar $progress -UniqueIdentifier "toast" -Verbose
foreach ($n in 1..100){
$binding['value'] = $binding['value'] + 0.01
$binding['text1'] = "hello"
Write-Output $binding
Update-BTNotification -UniqueIdentifier "toast" -DataBinding $binding -Verbose
Start-Sleep 1
}
But it doesn't seem to update ! The -Verbose doesn't show any error, and Write-Output $binding is clearly evidence $bindings is being updated every second...
I don't know what I'm doing wrong...
Thanks for any answer,
Silloky

Here is the code that works :
$progress = New-BTProgressBar -Title "Copying progress :" -Status "Downloading..." -Value 'value'
$image = New-BTImage -Source "$PSScriptRoot\icons\shell32_16739.ico" -Crop None
$button = New-BTButton -Dismiss -Content "OK"
$binding = #{
value = 0
}
New-BurntToastNotification -Text "Downloading your files...", "Your files are being downloaded so they can be available offline." -DataBinding $binding -UniqueIdentifier "001" -ProgressBar $progress -AppLogo $image
Start-Sleep 3
foreach ($n in 1..100){
Start-Sleep 0.5
$binding['value'] = $binding['value'] + 0.02
$null = Update-BTNotification -UniqueIdentifier "001" -DataBinding $binding
}
Remove-BTNotification -UniqueIdentifier "001"
New-BurntToastNotification -Text "Done !", "Your files are now available offline." -AppLogo $image -Button $button
Bye !

Related

How can I get results from Get-ADUser Filter in my Powershell script so I can validate if that user exists or not correctly?

FIXED: I did have to change if ($null -eq $FoundUser) and then if essentiall NULL -eq NULL, that user doesn't exist...
SORRY
I would really love some help as I've on/off been struggling with this logic with Get-ADUser for user creation.
I'm using Powershell 7.0 - 7.2.1 (latter currently) and having this problem with VSCode and running it in "console". We have a 2008 R2 forest but 2016 and 2019 DCs.
Essentially "Get-ADUser -Filter" doesn't return any value. I'm trying to use an if statement for if $null -ne $SamAccountName.
Any thoughts?
I thought I found the answer here but no luck for me.
$Users = Import-Csv -delimiter "`t" -Path "C:\Users\michel_m\Documents\Scripts\PowerShell\Staff\StaffData.txt"
#$sam = ""
#Generate data to use in creating user below
foreach ($User in $Users) {
$SAMAccount = $User.Username
$Filter = "sAmAccountname -eq '$SamAccount'
$FoundUser = Get-ADUser -Filter $Filter
Write-Host "HERE IS" $FoundUser
$results = $FoundUser.SamAccountName
#if ($null -ne $FoundUser)
if ($null -ne $results)
{
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
#NewUser_Function
($Dates + " - " + $user.username + " has been created") | out-file -filepath $OutputFile1 -append
#Write-Host "Pause 15 seconds"
Start-Sleep 15
Write-Host $user.username + " Has been created"
$Body = $user.username + " Has been created"
#schtasks.exe /run /s "OHDC01" /tn "GADS Sync - Users"
}
else
{
Write-Host $Filter
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
Write-Host $null is null
write-host $user.username + " already exists"
($Dates + " - " + $user.username + " already exists") | out-file -filepath $OutputFile2 -append
$Body = $user.username + " already exists",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\"
}
}
Output
HERE IS
sAmAccountname -like 'mangold_m' | Select-object SamAccountName
Are the results
#{FirstName=Michelle; LastName=Mangold; BuildingName=OAK; Position=Aide; Username=mangold_m; Email=mangold_m#Wonderfullife.org} is the user
mangold_m Is the SAM user
Is the found user
is null
mangold_m + already exists
HERE IS
sAmAccountname -like 'metzner_m' | Select-object SamAccountName
Are the results
#{FirstName=Melissa; LastName=Metzner; BuildingName=OHHS; Position=Aide; Username=metzner_m; Email=metzner_m#Wonderfullife.org} is the user
metzner_m Is the SAM user
Is the found user
is null
metzner_m + already exists
Thank you for updating you got your solution.
Here I also have tried from my side you can also use this small PowerShell script for validating the user existance.
$Users = Import-Csv -Path "C:\Users\RahulShaw\test.csv"
Foreach ($User in $Users){
$Username = $User.Username
$FoundUser = Get-ADUser -Filter "sAmAccountName -eq '$Username'"
$results = $FoundUser.SamAccountName
Write-Host $results
if($null -eq $FoundUser){
write-host "Username '$Username' does not yet exist in active directory"
}
else{
write-host "Username '$Username' exist in active directory"
}
}

Powershell Get-Service report wrong information

I've created a powershell script to list all domain controllers under current trusted forest, and than check each individual server for specific services if it's running or not and send an email with report.
I found 2 issues so far.
Get-Service -name "MyService" -ComputerName $myComputer "will say no service is found with that name, but if I list all the services : Get-Service -ComputerName $myComputer it will say "This operation might require other privileges." This is a problem because I'm reporting that the service doesn't exist but it is actually there.
For some reason if I just run the powershell script from command line manually it lists way more servers and most of the info is correct. But I schedule the powershell script from windows task manager with that same account the information is all wrong and it reports way less servers.
Script:
#$domain = [system.directoryservices.activedirectory.domain]::GetCurrentDomain().Name
#$numerOfDomainControlers= nslookup $domain
Clear-Content .\log.txt
$startTime = Get-Date
$allDCs = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Where-Object { $_.hostname -notlike '*root*' }).hostname
foreach( $allDC in $allDCs){
$testConnection = Test-Connection $allDC -Quiet -Count 1 -ErrorAction SilentlyContinue
Write-Host
if($testConnection -like "true") {
$SyncStatus = Get-Service -name "MyServicesName" -ComputerName $allDC -ErrorAction SilentlyContinue
if($SyncStatus.length -eq 0) {
Write-Host "MyServicesName doesn't exists on:"$allDC
$SyncStatus = "MyServicesName doesn't exists on:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
else{
write-host "MyServicesName on "$allDC "is: " $SyncStatus.status
$SyncStatus = "MyServicesName on " + $allDC + "is: " + $SyncStatus.status
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
else
{
Write-Host "Test Connection to Server failed:"$allDC
$SyncStatus = "Test Connection to Server failed:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
$endTime = Get-Date
$totalTime = New-TimeSpan -start $startTime -end $endTime
Write-Host $totalTime
$logs = "Total Time in Seconds:" + $totalTime |Out-File .\log.txt -Append
#send Email
$logs = Get-Content .\log.txt
$serverName = $env:computername
$LogTime = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$FromAddress = "email.com"
$ToAddress = "email.com"
foreach($log in $logs)
{
$Messagebody = $messagebody + $log + "`r`n" |Out-String
}
[string] $MessageSubject ="Status Report runing on " + $serverName +" " + $endTime
$SendingServer = "server"
Send-MailMessage -to $ToAddress -from $FromAddress -subject $MessageSubject -smtpServer $SendingServer -body $Messagebody -Attachments .\log.txt

Powershell locking first and last files and I cannot delete them without close powershell ISE

So I have a Powershell ISE ( tried running as administrator and w/o ) and it is created dummy .mdf file , 50 of them
Problem is that it holds onto the 1st and last , so copying or deleting them is not working ...
This is my script
param(
$amount = 50 # $(throw "Please give an amount of files to be created")
, $size = 5 # $(throw "Please give a the size of the files")
, $folder = "C:\dev\powershell\oldlocation" # $(throw "Please give an output folder wehere the files need to be created")
, $name = 'db' # $null
, $extension = '.mdf' # $null .mdf / .ldf
)
CLS
# Check for input
if(Test-Path $folder)
{
if($name -eq $null)
{
Write-Host "No filename given. Using default setting 'dummy'" -ForegroundColor Yellow
$name = 'dummy'
}
if($extension -eq $null)
{
Write-Host "No filename extension given. Using default setting '.txt'" -ForegroundColor Yellow
$extension = 'txt'
}
elseif($extension -contains '.')
{
$extension = $extension.Substring(($extension.LastIndexOf(".") + 1), ($extension.Length - 1))
}
for($i = 1; $i -le $amount; $i++)
{
$path = $folder + '\' + $name + '_' + $i + '.' + $extension
$file = [io.file]::Create($path)
$file.SetLength($size)
$file.Close
sleep 0.5
}
}
else{
Write-Host "The folder $folder doesn't exist" -ForegroundColor Red
Exit(0)
}
When () are omitted on a method, it returns the Overload Definitions. So the line where you are trying to close the file just needs ().
$file.Close()
If you see OverloadDefinitions ever returned, that's what to look for.

send mail after successfull powershell script execution

So I created the script below:
$target = "c:\$(get-date -F 'yyyy-MM')"
if (!(Test-Path $target)) {md $target}
gci 'c:\test\' -Filter *.xml -recurse | ?{!$_.PSIsContainer -and $_.CreationTime -ge (get-date "01.$((get-date).Month)")} | copy-item -Destination $target -Force
Could somebody point me to the right direction of how to send a email to a specific address after this script was successfully executed ?
As arco444 noted in his comment, send-mailmessage will allow you to send email from any machine running Powershell v2 or higher, as long as you have an accessible SMTP server.
you can try below solution in PowerShell
$EmailFrom = "someone1#company.com"
$EmailTo = "someone2#company.com"
$ccUsers="someone3#company.com"
$SMTPServer = "smtp.office365.com"
$port=587
$smtp = New-Object Net.Mail.SmtpClient($SMTPServer,$port)
$smtp.EnableSsl = "true"
$smtp.Credentials =New-Object System.Net.NetworkCredential($userName, $password);
$msg = New-Object Net.Mail.MailMessage
$msg.From = $EmailFrom
$msg.To.Add($EmailTo)
$msg.CC.Add($ccUsers)
$msg.IsBodyHTML = $true
$msg.Subject = "Test Subject";
#if you want to send some html in your email
$html = "<html><body><table width='100%'><tr bgcolor='#CCCCCC'><td height='25' align='center'> <font face='tahoma' color='#003399' size='4'><strong>Test Email from PowerShell</strong></font></td> </tr> </table></body></html>" $msg.Body = $html; $smtp.Send($msg);
If your using outlook, here is a example
[system.reflection.assembly]::loadwithpartialname("Microsoft.office.interop.outlook")
$OL=New-Object -ComObject OUTLOOK.APPLICATION
$ns =$OL.GETNAMESPACE("MAPI")
$mail =$ol.createitem(0)
$mail.recipients.add("something#live.nl")
$mail.CC=("something#ziggo.nl")
$MAIL.Subject= "$shortname"
#gets a signature
$mail.htmlbody= get-content $env:appdata\Microsoft\Signatures\*.txt
#for attachments..
$mail.Attachments.Add($file.FullName)
$lines=get-content $filename
$lines+=get-content $env:appdata\Microsoft\Signatures\*.txt
clear-variable text
foreach ($line in $lines)
{
$text += $line + "`r`n"
}
$mail.body= $text
$mail.display()

Powershell Script to Add New Users in AD for HR Department

I'm trying to come up with a powershell script to add new users in AD that our HR department can use instead of sending me emails about that.
My script will ask for which department they wanna add the new user, username and the full name:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0 {"You selected RN."}
1 {"You selected Call Center."}
2 {"You selected Management."}
3 {"You Selected Billing."}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$result,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";
Each time I try I run it I get this error message:
New-ADUser : Directory object not found At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:84
char:1
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (CN=TYoussef Tes...diatrics,DC=Com:String) [New-ADUser], ADIdentityNotFo
undException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
icrosoft.ActiveDirectory.Management.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'yousseft'
under: 'DC=TribecaPediatrics,DC=com'. At
C:\Users\youssef\AppData\Local\Temp\ofit4gnq.1lp\AddUserHR.ps1:92
char:1
+ Add-ADGroupMember "Users" "$UName";
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (yousseft:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.
AddADGroupMember
$result comes back as an integer so the path you're giving to New-ADUser looks like this:
"CN=Users,OU=0,DC=Domain,DC=com"
Which is why you're getting that error message, because more than likely there is no OU with the name "0" or any of the other options "1","2" or "3".
In your switch statement you should declare what each departments OU is called so you can put the new user into that OU.
you were very close, here's how i would modify your switch statement:
# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
Write-Warning 'Current user does not have Administrator rights'
Write-Host 'Attempting to copy files to temporary location and restarting script'
# Get random file name
Do {
$temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
} Until (!(Test-Path -LiteralPath "$temp"))
# Create directory
Write-Host 'Creating temp directory... ' -NoNewLine
New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
Write-Host 'done.'
# Copy script to directory
Write-Host 'Copying script to temp directory... ' -NoNewLine
Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
Write-Host 'done.'
$newScript = "$($temp)\$($myInvocation.MyCommand.Name)"
# Start new script elevated
Write-Host 'Starting script as administrator... ' -NoNewLine
$adminProcess = New-Object System.Diagnostics.ProcessStartInfo
$adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
$adminProcess.Arguments = " -File `"$newScript`""
$adminProcess.Verb = 'runas'
Try {
[System.Diagnostics.Process]::Start($adminProcess) | Out-Null
}
Catch {
Write-Error 'Could not start process'
Exit 1
}
Write-Host 'done.'
Exit 0
}
#Change the execution policy
Set-ExecutionPolicy bypass
#Import the AD module
Import-Module ActiveDirectory
#Set variables
$title = "Add Users To The Domain"
$message = "For which department do you wanna add this user to?"
$rn = New-Object System.Management.Automation.Host.ChoiceDescription "&RN", `
"RN"
$callcenter = New-Object System.Management.Automation.Host.ChoiceDescription "&Call Center", `
"Call Center"
$management = New-Object System.Management.Automation.Host.ChoiceDescription "&Management", `
"Management"
$billing = New-Object System.Management.Automation.Host.ChoiceDescription "&Billing", `
"Billing"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($rn, $callcenter, $management, $billing)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0
{
"You selected RN."
$OU = "RN"
}
1
{
"You selected Call Center."
$OU = "CallCenter"
}
2
{
"You selected Management."
$OU = "Management"
}
3
{
"You Selected Billing."
$OU = "Billing"
}
}
$UName = Read-Host "What is the username you wanna give? Make sure it matches the username in the email."
$FName = Read-Host "What is the Full Name of the user?"
New-ADUser `
-Name $FName `
-Path "CN=Users,OU=$OU,DC=Domain,DC=com" `
-SamAccountName $UName `
-DisplayName $FName `
-AccountPassword (ConvertTo-SecureString "password1" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
Add-ADGroupMember "Users" "$UName";

Resources