Check if an user is member of a local group using PowerShell

We can easily find a local user is member of a local group by accessing ADSI WinNT Provider. In this post, I am going to share powershell script to check if local user is exists in a group, and check multiple users are member of a local group.

Check if local user is member of Administrators group

The following powershell commands checks whether the given user is member of built-in Administrators group.

$user = "Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$membersObj = @($groupObj.psbase.Invoke("Members")) 

$members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)})

If ($members -contains $user) {
      Write-Host "$user exists in the group $group"
 } Else {
        Write-Host "$user not exists in the group $group"
}

Check if multiple users are member of a given local Group

Run the below powershell command to check if multiple users are member of a given group.

$users = "Morgan","TestUser1","TestUser2"
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group" 
$membersObj = @($groupObj.psbase.Invoke("Members")) 

$members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)})

ForEach ($user in $users) {
If ($members -contains $user) {
      Write-Host "$user exists in the group $group"
 } Else {
        Write-Host "$user not exists in the group $group"
}}

Check if users are member of a group in Remote Computer

Use the below powershell command to check if users are member of a given group in remote machine/server.

$computer = "remote-pc" 
$users = "Morgan","TestUser1","TestUser2"
$group = "Administrators";
$groupObj =[ADSI]"WinNT://$computer/$group,group" 
$membersObj = @($groupObj.psbase.Invoke("Members")) 

$members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)})

ForEach ($user in $users) {
If ($members -contains $user) {
      Write-Host "$user exists in the group $group"
 } Else {
        Write-Host "$user not exists in the group $group"
}}
Advertisement

1 thought on “Check if an user is member of a local group using PowerShell”

  1. User Adspath instead of name. This solves the domain issue

    $computer = "remote-pc"
    $users = "Morgan","TestUser1","TestUser2"
    $group = "Administrators";
    $groupObj =[ADSI]"WinNT://$computer/$group,group"
    $membersObj = @($groupObj.psbase.Invoke("Members"))

    $members = ($membersObj | foreach {$_.GetType().InvokeMember("AdsPath", 'GetProperty', $null, $_, $null)})

    ForEach ($user in $users) {
    If ($members -contains $user) {
    Write-Host "$user exists in the group $group"
    } Else {
    Write-Host "$user not exists in the group $group"
    }}

    Reply

Leave a Comment