Powershell – Get local User group members – Powershell

powershellsecurity-groups

$Output = 'C:\temp\Result.txt'
$Servers = Get-Content 'C:\temp\ServerNames.txt'
$ScriptBlock = {

$Groups = Get-WmiObject Win32_GroupUser -ComputerName $Servers 
$LocalAdmins = $Groups | Where GroupComponent –like '*"Administrators"'

$LocalAdmins |% {  
$_.partcomponent –match ".+Domain\=(.+)\,Name\=(.+)$" > $nul  
$matches[1].trim('"') + "\" + $matches[2].trim('"')
}
}
foreach ($ServerNames in $Servers) {
"Local Admin group members in $ServerNames" | Out-File $Output -Append
Invoke-command -ScriptBlock $ScriptBlock -ComputerName $ServerNames | Out-  File $Output -Append
}

I am using the above mentioned script to get local admins group members to run against multiple servers, I am getting error –

Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the
command again.
+ CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand
+ PSComputerName : Computer

Can you pls assist me to correct that…?

Server Names in the file ServerNames.txt are in this format mentioned below –

ServerNames.txt

Best Answer

$Output = 'C:\temp\Result.txt'
$Servers= Get-Content 'C:\temp\ServerNames.txt'
$ScriptBlock = {
    $Groups = Get-WmiObject Win32_GroupUser -ComputerName $Using:ServerName
    $LocalAdmins = $Groups | Where GroupComponent –like '*"Administrators"'
    $LocalAdmins | ForEach-Object {  
        If($_.partcomponent –match ".+Domain\=(.+)\,Name\=(.+)$"){  
            $matches[1].trim('"') + "\" + $matches[2].trim('"')
        }
    }
}
ForEach ($ServerName in $Servers) {
    "Local Admin group members in $ServerName" | Out-File $Output -Append
    Invoke-command -ScriptBlock $ScriptBlock -ComputerName $ServerName | Out-File $Output -Append
}

But IMO this could be a bit simplified without the unnecessary vars

$Output = 'C:\temp\Result.txt'
$Servers= Get-Content 'C:\temp\ServerNames.txt'
$ScriptBlock = {
    Get-WmiObject Win32_GroupUser -ComputerName $Using:ServerName |
    Where GroupComponent –like '*"Administrators"'|
    ForEach-Object {  
        If($_.partcomponent –match ".+Domain\=(.+)\,Name\=(.+)$"){  
            $matches[1].trim('"') + "\" + $matches[2].trim('"')
        }
    }
}
ForEach ($ServerName in $Servers) {
    "Local Admin group members in $ServerName" | Out-File $Output -Append
    Invoke-command -ScriptBlock $ScriptBlock -ComputerName $ServerName | Out-File $Output -Append
}