We help IT Professionals succeed at work.

Determining if something exists in Powershell

Adam Brown
Adam Brown used Ask the Experts™
on
This is going to be kind of a weird one to explain.
I'm trying to write a code that will go through an AD Domain and build Security Groups for each OU, placing them in a specific, separate OU. I have the code for this already, it works great, but I want to add a little more functionality.

What I'm wondering is, what would I do in an if statement to determine if a security group exists or if a user is already a member of a group, etc. etc. etc.

Basically, if I wanted to write a script that looked through an OU for users, and checked to see if they were already a member of a specific security group, what would that look like?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
PowerShell Developer
Top Expert 2010
Commented:

What are you using in your script at the moment? Quest? MS AD? Or native PS (System.DirectoryServices)?

In AD that normally means checking like this:

If ((Get-QADGroup "Something") -eq $Null) {
  "Something does not exist"
}

The same can be done with the MS AD CmdLets. If you're using Native it's a bit harder but the method is still pretty sound.

> Basically, if I wanted to write a script that looked through an OU for users, and checked
> to see if they were already a member of a specific security group, what would that look like?

Get-QADUser -SearchRoot "domain.com/somewhere" -NotMemberOf "YourGroup"

If you're using DirectoryServices you'd be looking at building a filter like this:

(!(memberOf=CN=YourGroup,OU=groups,DC=domain,DC=com))

The search based will be used in conjunction with that to limit the results.

HTH

Chris
Adam BrownSenior Systems Admin
Top Expert 2010

Author

Commented:
That helps a lot with one part of the problem I'm working on. Right now I am working mostly with the native commands, since I need to build scripts that basically run right out of the box without additional downloads. Basically, I've been tasked with developing the scripts necessary to build an AD environment up from CSVs and additional scripts to keep them maintained. And I just started working with powershell like a month ago :S