≡ Menu
Deep in the Code

Using PowerShell to Check if a Particular User is in the Local Administrators Group

PowerShell is a very powerful tool for Windows administrators and developers alike.

I wanted to find out if a particular user ID was in the local admin group on all servers in my domain. Fortunately, someone had written a script (source link no longer exists) to check that very thing on the server you’re logged onto.

However, I wanted to check not just the server I’m on, but on all servers in the domain.

The script below, called findadmins.ps1, should do just that:

$userToFind = $args[0] 

$servers = Get-ADComputer -Filter {OperatingSystem -Like "Windows *Server*"} -Property * | Format-Table Name,OperatingSystem,OperatingSystemServicePack -Wrap -Auto

foreach ($server in $servers) {

	$administratorsAccount = Get-WmiObject Win32_Group -ComputerName $server -filter "LocalAccount=True AND SID='S-1-5-32-544'" 
	$administratorQuery = "GroupComponent = `"Win32_Group.Domain='" + $administratorsAccount.Domain + "',NAME='" + $administratorsAccount.Name + "'`"" 
	$user = Get-WmiObject Win32_GroupUser -filter $administratorQuery | select PartComponent |where {$_ -match $userToFind} 
	$user.PartComponent.Replace("\\","").Split("\", 2, [System.StringSplitOptions]::None)[0]


You should be able to run this at the PS command prompt like this, once you’ve changed to the directory where the script is: “.\findadmins.ps1 userid”.

I have not completely finished testing this, as I got a series of errors, though these errors do not appear to be due to errors in the script itself.