I would like to write a line that lets me know any usernames that could not be found and what their display name was within the .txt document that the script is pulling from.
Essentially I just want a line to add onto the existing script.
Any tips or guidance on how to do so would be much appriciated.
Get-Content C:\Users\User\Desktop\findusername.txt | Foreach-Object {get-aduser -filter "displayName -like '$($_)'" | Select-Object SamAccountName} | Export-Csv -Path C:\Users\User\Documents\ADGroupusernames.csv -NoTypeInformation
CodePudding user response:
As Santiago points out, filter does not throw an error when no matching objects are found. You can instead check to see if any objects are returned and react to that.
Get-Content C:\Users\User\Desktop\findusername.txt |
ForEach-Object {
if ($found = Get-ADUser -Filter "displayName -like '$($_)'") {
$found | Select-Object SamAccountName
}
else {
[PSCustomObject]@{
SamAccountName = "Did not find '$_'"
}
}
} | Export-Csv -Path C:\Users\User\Documents\ADGroupusernames.csv -NoTypeInformation