I currently use a script to display all computers assigned to a security group. The script I currently use is a VB Script:
Set objGroup = GetObject("LDAP://cn=My Group,ou=Security Groups,ou=_Groups - standard,ou=city,ou=state,dc=my,dc=domain,dc=tld,")
For Each objMember in objGroup.Members
Wscript.Echo objMember.Name
Next
This script works and pulls every member of My Group from the entire domain. This works, but I'm trying to filter it a bit. I want to search computers through a specific OU. I have tried the following code to no avail:
Dim objGroup
Dim objMachine
Dim objMatch
Set objGroup = GetObject("LDAP://cn=My Group,ou=Security Groups,ou=_Groups - standard,ou=city,ou=state,dc=my,dc=domain,dc=tld")
Set objMachine = GetObject("LDAP://ou=Building,ou=street,ou=city,ou=state,dc=my,dc=domain,dc=tld")
Dim c
For each c in objGroup
if c = objMachine Then
Wscript.Echo objMachine.Name
end if
next
The code executes without error, but I do not see any output. I then decided to tackle this problem in PowerShell.
$computer = Get-ADGroup -searchbase 'ou=Building,ou=street,ou=city,ou=state,dc=my,dc=domain,dc=tld' -Filter * ` |
Get-ADGroup -Filter {(Name -eq "My Group") -or (Name -eq "My Other Group")} ` |
Select-Object -Unique ` |
Sort-Object DistinguishedName;
$computer | Select-Object Name, DistinguishedName;
export-csv C:\Temp\Result.csv
This throws a few errors in ISE stating that the cmdlet Get-ADGroup doesn't support pipeline input or the input didn't match. At the end, it lists the two groups, as well as their distinguished names.
I would like to get a computer name as well as the Distinguished Name for every computer that is a member of either "My Group" or "My Other Group" in the Building OU as well as each OU under that OU. I would prefer a way to do it in PowerShell, but I can use VB Script as well.
(Sorry if I'm missing any critical information, this is my first posting.)
Break this task into:
Finding group members is easy with Get-ADGroupMember
:
$Members = Get-ADGroupMember "SecurityGroup"
To determine whether a member resides in an OU, check to see if the OU distinguished name matches the last part of the Member's distinguished name:
$OU = "OU=Specific,OU=Computers,OU=Office1,DC=domain,DC=tld"
$MembersInOu = $Members |Where-Object {$_.DistinguishedName -like "*,$OU"}
You can now combine this into a single pipeline:
Get-ADGroupMember "SecurityGroup" |Where-Object {$_.DistinguishedName -like "*,$OU"}