Aug 19 2021 09:30 AM - edited Aug 19 2021 10:57 AM
Hello all
I have the following script that looks for all disabled users that have a value in the "manager" attribute. It works, however if no results are the script sends an email. I would like the script to not send an email if no results are found.
Thank you in advance.
Query all users all disabled users and remove value from manager attribute
#>
Remove-Item -Path C:\Temp\DisabledUsers\*.csv -Force
$smtpFrom = "AllADusers@example.com"
$smtpServer = "XXXX"
$today = Get-Date -Format yyyyMMdd
$smtpto = ""
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$ToDay =Get-date -Format yyyMMdd
Import-Module activedirectory
$Disabled = Get-ADUser -Filter * -Properties samaccountname,manager,enabled | where {$_.manager -notlike $null -and $_.enabled -eq $False} |select samaccountname,enabled,manager,distinguishedname
$Disabled | Export-Csv -path C:\Temp\DisabledUsers\$today.csv -NoTypeInformation
$message.Subject = ("Disabled users that currently have manager. Manager wil be removed "+$today)
$disabledUser = Get-Item C:\Temp\DisabledUsers\$today.csv
$att3 = new-object Net.Mail.Attachment($disabledUser)
$message.Attachments.Add($att3)
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtpFrom
$smtp.Send($message)
$message.Attachments.Remove($att3)
$Disabled = Import-Csv -Path C:\Temp\DisabledUsers\$today.csv
$Disabled |ForEach-Object {Set-ADUser -Identity $_.samaccountname -Manager $null}
Aug 19 2021 10:05 AM - edited Aug 19 2021 10:06 AM
Solution@Skipster311-1Try the modified version below. Also, might be wise to remove your email addresses :) Two modifications:
1) Put a check around the code to send the email and make the AD changes to determine if there were any disabled users present in the $Disabled variable
2) There's no need to read the disabled users again from the CSV file, you already have them in the $Disabled variable
Remove-Item -Path C:\Temp\DisabledUsers\*.csv -Force
$smtpFrom = "AllADusers@vixxo.com"
$smtpServer = "BOS-EXC2016"
$today = Get-Date -Format yyyyMMdd
$smtpto = "XXX,XXX,XXX"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$ToDay =Get-date -Format yyyMMdd
Import-Module activedirectory
$Disabled = Get-ADUser -Filter * -Properties samaccountname,manager,enabled | where {$_.manager -notlike $null -and $_.enabled -eq $False} |select samaccountname,enabled,manager,distinguishedname
$Disabled | Export-Csv -path C:\Temp\DisabledUsers\$today.csv -NoTypeInformation
if ($Disabled) {
$message.Subject = ("Disabled users that currently have manager. Manager wil be removed "+$today)
$disabledUser = Get-Item C:\Temp\DisabledUsers\$today.csv
$att3 = new-object Net.Mail.Attachment($disabledUser)
$message.Attachments.Add($att3)
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtpFrom
$smtp.Send($message)
$message.Attachments.Remove($att3)
$Disabled |ForEach-Object {Set-ADUser -Identity $_.samaccountname -Manager $null}
}
Aug 19 2021 10:43 AM