I am trying to write a PowerShell script that will find all of the users in AD that have not logged in for six months, and to not include anyone in the Terminated Users OU or the Terminated Users\vendors and others OU. I can't seem to get it to exclude either OU. The six month part of the search works perfectly.
Here is my current code:
Search-ADAccount -accountinactive -datetime (get-date).AddMonths(-6) -usersonly | ft Name,LastLogonDate | ? {$_.DistinguishedName -notlike "*ou=Terminated Users,*" -and $_.DistinguishedName -notlike "*ou=vendors and others,*"} | Out-File stale_users.txt
I have removed the ,* from the end of the OU names, tried -or, and tried just each one of the OU's by themselves. It still does not skip searching those OU's.
Swap the order of your exclusion code and the "ft" or "Format-Table". You're formatting your data down to where it doesn't have the DistinguishedName field and then trying to match against that missing field.
Search-ADAccount -accountinactive -datetime (get-date).AddMonths(-6) -usersonly | `
? {$_.DistinguishedName -notlike "*ou=Terminated Users,*" -and $_.DistinguishedName -notlike "*ou=vendors and others,*"} |`
ft Name,LastLogonDate |`
Out-File stale_users.txt