mattmscott
6/26/2019 - 5:31 PM

Get Computer AD Groups

# Get the hostname and append a $ on the end
$hn = $hostname + "$"
$groupList = ""
# Get the list of groups that the machine is a member of other than Domain Computers
# If tehre aren't any set it to blank.
try{
    $groups = (New-Object System.DirectoryServices.DirectorySearcher("(&(objectCategory=Computer)(samAccountName=$($hn)))")).FindOne().GetDirectoryEntry().memberOf
    foreach($group in $groups){
        $group = $group.split(',')[0]
        $group = $group.split('=')[1]
        $groupList = $groupList + $group + ','
    }
    $groupList = $groupList.Substring(0, $groupList.Length-1)
}

catch{
    $groupList = ""
}

echo $groupList