Last active
January 14, 2020 18:42
-
-
Save dpo007/b209ae9adf97eb4a72f522cb6599e95a to your computer and use it in GitHub Desktop.
PowerShell function :: Check if domain-joined computer is a member of AD group, without AD module.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ComputerIsInGroup { | |
param ( | |
[Parameter(Mandatory=$True)] | |
[string]$GroupName | |
) | |
# Get computer's DN | |
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher | |
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry | |
$objSearcher.Filter = "(&(objectCategory=Computer)(SamAccountname=$($env:COMPUTERNAME)`$))" | |
$objSearcher.SearchScope = "Subtree" | |
$obj = $objSearcher.FindOne() | |
$computer = $obj.Properties["distinguishedname"] | |
# Now get the members of the group | |
$objSearcher.Filter = "(&(objectCategory=group)(SamAccountname=$GroupName))" | |
$objSearcher.SearchScope = "Subtree" | |
$obj = $objSearcher.FindOne() | |
[String[]]$members = $obj.Properties["member"] | |
return ($members -contains $computer) | |
} | |
# Example usage: | |
# If (ComputerIsInGroup "Workstations") { Write-Host 'Computer is a member.' } else { Write-Host 'Computer is Not a member.' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment