如何通过PowerShell检查用户帐户组是否存在?

the*_*ser 2 powershell powershell-2.0

像这样的东西:

if(GroupExists("Admins")) // <-- How can I do this line ?
{
    ([ADSI]"WinNT://$_/Admins,group").add($User)
}
else
{
    $Group = Read-Host 'Enter the User Group :'
    ([ADSI]"WinNT://$_/$Group,group").add($User)
}
Run Code Online (Sandbox Code Playgroud)

Tay*_*ibb 8

您可以使用Exists静态方法,如下所示:

[ADSI]::Exists("WinNT://localhost/Administrators")
Run Code Online (Sandbox Code Playgroud)

要获得True/False结果,您可以将其包装到try/catch语句中.

$result = try { [ADSI]::Exists("WinNT://localhost/Administrators") } catch { $False }
Run Code Online (Sandbox Code Playgroud)

或者在if/then语句中,你需要将它包装在一个 $()

if ( $(try {[ADSI]::Exists("WinNT://localhost/Administrators")} catch {$False}) ) {
    write-host "good"
    }
else {
    write-host "bad"
    } 
Run Code Online (Sandbox Code Playgroud)