I do a monthly report on inactive accounts and would like to send an email to the managers who are responsible for the service accounts to notify them that the accounts have not been used for more than 30 days based on my data. csv file. When I run my script it only shows one user in the email for each entry in the csv file.
$Users =
@"
Manager;inactiveADAccount
[email protected];test_1;test_2;test_3
[email protected];test_4
"@ | ConvertFrom-Csv -Delimiter ";"
ForEach($Manager in $Users) {
$bodytxt = @"
Hello,
Please verify users below
$($Manager.inactiveADAccount)
"@
$Message = New-Object System.Net.Mail.MailMessage
$Message.From = New-Object System.Net.Mail.MailAddress '[email protected]'
$To = $Manager.Manager
$Object = "Inactive Accounts"
$body = $bodytxt
$SMTPServer = 'mail.domain.com'
Send-MailMessage -From $Message.From -To $To -Subject $Object -Body $body -BodyAsHtml -SmtpServer $SMTPServer -Priority High -Encoding UTF8
}
CodePudding user response:
Your CSV file is not constructed correctly.
See the results of your CSV File:
Manager inactiveADAccount
------- -----------------
manager_1@domain.com test_1
manager_2@domain.com.ca test_4
As you can see test_2 and test_3 users are omitted from the csv...
Use one row for each user and manager, this should be:
$Users =
@"
Manager;inactiveADAccount
[email protected];test_1
[email protected];test_2
[email protected];test_3
[email protected];test_4
"@ | ConvertFrom-Csv -Delimiter ";"
Which now includes all the users:
Manager inactiveADAccount
------- -----------------
manager_1@domain.com test_1
manager_1@domain.com test_2
manager_1@domain.com test_3
manager_2@domain.com.ca test_4
Then Group The results and send the mail:
foreach ($Manager in $Users | group Manager) {
$bodytxt = @"
Hello,
Please verify users below
$($Manager.Group.inactiveADAccount | Out-String)
"@
[...]