Admit it. Be honest now. We’ve all done it. We’ve run a command against a batch of users and forgot to limit the scope to the ones we were really targeting.
I recently had to write a small Powershell-based application that loads all the users in a domain (filtered to exclude service accounts and admins) into a combobox. Once loaded, the user of the application can select the one user that they are trying to affect. The tricky part is that there is an if clause to run extra commands on the target if their OU has a specific parent OU, and not run those commands if their OU has a different parent OU. So, how do you tell Powershell to check for OU membership? The AD DistinguishedName property has the answer, but you have to tell Powershell how to read it.
$distinguishedName = Get-ADUser -Server dc.domain.com -Identity username -Properties DistinguishedName | Select -Property DistinguishedName if($distinguishedName -split "," -contains "OU=Targeted") { Get-ADUser -Server dc.domain.com -Identity username | Set-ADUser -ChangePasswordAtLogon $true }
The -split ","
is the key that tells Powershell how to parse the DistinguishedName property. Once Powershell parses the property, then the -contains
can properly search the string for a match.
Leave a comment