Bite Size Bytes

Small coding solutions to big problems


Run a Powershell command based on OU Membership

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Me

As a seasoned IT professional, I have developed an extremely well-rounded breadth and depth of knowledge and an exceptional ability to decipher and communicate complex issues. I have years of proven experience in IT leadership roles, security auditing, digital forensics, and overseeing development of custom applications, rounded out with a Bachelor of Science degree in Information Technology emphasizing Software Development. Over the course of my career, I have successfully held certifications as a GIAC Certified Incident Handler (GCIH), as well as CIW, CompTIA, and assorted Microsoft programming and networking certs. I have presented at the 2019 CETPA Conference in Anaheim and the 2021 CITE Conference in Sacramento.

Codementor badge