I am new to PowerShell and I am trying to get a list of Active Directory items that start with the same naming convention for example I have a number of groups beginning with "ABC_Group1", "ABC_Group2", "ABC_Group3".
I know that:
get-adgroup "ABC_Group1" will list that specific group
'get-adgroup -filter * | sort name | select Name' will list all the groups but I don't know how to filter to find just the specific groups starts with "ABC_"
I then want to list it's members.
33 Answers
You can use Wildcard search with Where condition. In the newer PS version, the where clause can be used as Filter
Import-Module ActiveDirectory Get-ADGroup -Filter {Name -like 'ABC_*'} -Properties * | select -property SamAccountName,Name,Description,DistinguishedName,CanonicalName,GroupCategory,GroupScope,whenCreated Since the OP asked to get the members of the group as well, here is the piece of code which will help you:
Get-ADGroup -Filter {Name -like 'ABC_*'} -SearchBase "DC=YourDC" | Get-ADGroupMember -Partition "DC=YourDC" OR
Get-ADGroup 'Group Name' -Properties Member | Select-Object -ExpandProperty Member OR use Dot notation:
(Get-ADGroup 'Group Name' -Properties Member).Member Hope this helps.
2I've done some research and played around with the code and it turns out,
Get-ADGroup -Filter "name -like '*ABC_*'" | sort name lists all the groups that have "ABC_"
However, this also means it will list directories such as "Group_ABC_". However, I only want to list directories that START with "ABC_"
Well, wouldn't it be enough to just remove the "*" in front of the ABC?
So '*ABC_*' would turn into 'ABC_*' and therefore be Get-ADGroup -Filter "name -like 'ABC_*'" | sort name
I highly recommend you to read yourself into Regular Expressions, you wont need it for this task but it can make you're life so much easier regarding pattern matching in strings and similar cases