I came across this great little gold nugget of a 1-liner while reading this blog post on automating Outlook Profile creation, so all props go to Travis Runyard for this one.
([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof
To break it down, this is using the [ADSISEARCHER] type accelerator to create an instance of the DirectorySearcher class.
The string specified directly after the accelerator denotes the search filter, so in this case, we’ll only be searching for objects with a samaccountname attribute that matches the current user’s logon name.
There’s only ever going to be one object returned, so we use the FindOne method to return a single System.DirectoryServices.SearchResult object.
All that’s left after that, is to get the contents of the “memberof” property on that object.
In his blog post, Travis goes one step farther and uses a regex to remove the LDAP path elements like “CN=” which leaves us with just the group names. Very smart!
([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'
If we store the results of this search in a variable, for example $userGroups, we can then check if the user is a member of a certain group:
Alternatively, you could use comparison operators like –contains, –ccontains for a case-sensitive comparison, or even –notcontains.
([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1' -ccontains "Colour Printing"
Hey.
Thank you for the post. Most usefull! But how would you store the search in a variable?
LikeLike
Hi Tobias. Just put “$variableName =“ in front of the one-liner.
LikeLike
Yes, i figured. I just overcomplicated it. Got it working. Absolutly perfect line of code for my project.
Thanks. Ill keep watching your site:)
LikeLike
Bare hyggelig
LikeLike