Wednesday, 4 October 2017

PowerShell : Check if user is member of local Adminstrators group

We can find whether the given user is member of local Administrators group or not by accessing ADSI WinNT Provider. In this post, I am going to write powershell script to check if an user is exists in local Administrators group in local machine and remote server.

Check if user is member of local Administrators group:

The following powershell commands checks whether the given user is member of Administrators group in local machine.
$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"
}

Find if user is member of local Admins group in Remote server:

Use the below powershell command to check if user is member of Administrators group in remote computer.
$computer = "hp-pc" 
$user = "Morgan";
$group = "Administrators";
$groupObj =[ADSI]"WinNT://$computer/$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 Administrators group:

Use the below powershell script to check if multiple users are member of local Admins 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"
}}

Advertisements
Advertisements

1 comment:

  1. This is really god blog with good tips! Thanks for writing!

    ReplyDelete