Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Solution proposed by @Mark didn't work for me (Windows Server 2016), this one worked

Search-ADAccount -accountinactive -datetime (get-date).AddMonths(-6) -usersonly | `
  ? {$_.DistinguishedName -notmach "ou=Terminated Users|ou=vendors and others"} |`
  ft Name,LastLogonDate |`
  Out-File stale_users.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top