If get-aduser works, then $FoundUser will be incremented by one.
If get-aduser fails, then $UnknowUser will be incremented by one.
$FoundUser + $UnknowUser will equal the total number of rows in the csv.
If $OUNames -contains $OU, then $GotOne will be incremented by one. (Assuming that you corrected my typo error )
If the OU test fails, then $NotInOU will be incremented by one.
$Gotone + $NotinOU will equal $FoundUser.
If $NotInOU is greater than one, or $UnknowUser is greater than one, then the current object (dollar underscore) will be added to the $WhoAreThesePeople array.
If your csv only has one row in it, does $FoundUser equal one? If not, go figure out what is wrong as to why it's not finding the user.
Once get-aduser works, does $NotInOU equal 1? If it does, analyze the OU names to figure out why it's not working. Does $OU.gettype() show that it is a string? Does $OU.length match the number of characters that visually display on the screen?
Here is an updated script with more diagnostics. Please post the entire output of this.
Be advised that I don't have a good way to test this. It may contain mistakes.
$WhoAreThesePeople = @()
$FoundUser = 0
$GotOne = 0
$NotInOU = 0
$UnknowUser = 0
$OUNames = "OU=FMI,OU=Cognizant,OU=FM Users,OU=Corp,DC=test-tech,DC=com", "OU=BPO and RPA,OU=Cognizant,OU=Consultants,OU=Users,OU=Corp,DC=test-tech,DC=com"
Import-Csv C:\temp\test2.csv |
ForEach-Object {
$u = get-aduser -Filter "userPrincipalName -eq '$($_.upn)'"
if ($u) {
$FoundUser++
$OU = $u.DistinguishedName.Substring($u.DistinguishedName.IndexOf('OU=',[System.StringComparison]::CurrentCultureIgnoreCase))
if ($OUNames -contains $OU) {
$GotOne++ # fixed per Rich
Set-ADAccountExpiration -Identity $u.distinguishedName -TimeSpan 90.0:0
} else {
$NotInOU++
$WhoAreThesePeople+= $_
"A user was added to WhoAreThesePeople because we did not find the OU."
"The OU we tested is {0}" -f $OU
"The OU variable type is {0} " -f $OU.gettype().Name
"The string length is {0}" -f $OU.length
"Current WhoAreThesePeoplecount is {0}" -f $WhoAreThesePeople.count
}
} else {
$UnknowUser++
$WhoAreThesePeople+= $_
"An unknown user was added to WhoAreThesePeople. Current count is {0}" -f $WhoAreThesePeople.count
}
}
"We found {0} users." -f $FoundUser
"Of the users that we found, {0} were NOT in the OU." -f $NotInOU
"Expiration was set on {0} users." -f $GotOne
"Count of users NOT found in AD: {0}" -f $UnknowUser
"Total WhoAreThesePeople count is {0}" -f $WhoAreThesePeople.count
$WhoAreThesePeople | Export-Csv C:\temp\WhoAreThesePeople.csv -NoTypeInformation