获取本地用户组成员 - Powershell

获取本地用户组成员 - Powershell
$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
}

我正在使用上面提到的脚本让本地管理员组成员针对多台服务器运行,但出现了错误 -

无法验证参数“ComputerName”的参数。该参数为 null 或为空。请提供一个非 null 或为空的参数,然后重试该命令。+ CategoryInfo : InvalidData: (:) [Get-WmiObject],ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand + PSComputerName : Computer

你能帮助我纠正这个问题吗……?

ServerNames.txt 文件中的服务器名称采用以下格式 -

服务器名称.txt

答案1

$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
}

但在我看来,如果没有不必要的变量,这可以稍微简化一点

$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
}

相关内容