简体   繁体   中英

How can I check if a User Account group exists through powershell?

Something like this :

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

You can use the Exists static method as follows:

[ADSI]::Exists("WinNT://localhost/Administrators")

To get a True/False result you can wrap into try/catch statement.

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

or in a if/then statement you'll need to wrap it inside a $()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM