all, PowerShell n00b here. Enjoying it so far!
I've got a list of users that I need to compare against AD.
I've created a script to search for Get-ADUser Name and EmailAddress for each user, using an array of Divisions as filter.
If AD user is found, write-host user found, show Name, EmailAddress! Easy enough.
If AD use is NOT found, keep looping through all Divisions until the last one, if not found in any Division, print ONLY ONCE "user not found in AD"
I've been playing around with various Do-While, Do-Until loops and If-ElseIf statements but I can't figure out to get it to report only ONCE if not found in any division.
Please help! Thanks, in advance! :)
$Divisions="1","2","3"
$lastd = $Divisions | Select-Object -Last 1
Foreach ($d in $Divisions){
$aduser = Get-ADUser -Filter "Surname -like '*$lastname' -and GivenName -like '$givenname*'`
-and Enabled -eq '$True' -and Division -eq '$d'"`
-SearchBase "OU" -Properties Name, Division, EmailAddress |Select-Object Name,Division,EmailAddress
if(!$aduser){
write-host "Usernotfound"
}
if($aduser -eq ""){
write-host "user not found in AD" `n
}
else{
write-host "User Found in $d :" $aduser.Name $aduser.EmailAddress -F Green `n
}
}
Here's a sample result when I run script.
USER1 - account will be terminated in 35 days; Last signon activity 2 days ago
****Searching: Active Directory Information
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
User Found in Division1! Name EmailAddress
USER2 - account will be terminated in 43 days; Last signon activity 4 days ago
****Searching: Active Directory Information
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
User Found in Division2! Name EmailAddress
Usernotfound
Usernotfound
Usernotfound
I'm sure this is easy stuff for your PS warriors, but I'm dyin here. How can this be done better? Thanks!
CodePudding user response:
Since your foreach
loop seems to pertain only to a single user (while iteratively looking for that one user in multiple divisions), you can simply move your not-found test to after the loop:
foreach ($d in $Divisions) {
$aduser =
Get-ADUser -Filter "Surname -like '*$lastname' -and GivenName -like '$givenname*' -and Enabled -eq 'True' -and Division -eq '$d'" -Properties Name, Division, EmailAddress |
Select-Object Name,Division,EmailAddress
if ($adUser) {
Write-Host "User Found in $d :" $aduser.Name $aduser.EmailAddress -F Green `n
break # Presumably you needn't keep searching.
}
}
if (-not $aduser) {
Write-Host "Usernotfound"
}