PowerShell:如何删除服务器上的安全组?

时间:2014-01-17 03:35:29

标签: powershell

如何使用PowerShell脚本删除服务器上的Windows安全组?

我有一项任务是删除所有旧用户组,并希望自动化该过程以节省时间。

1 个答案:

答案 0 :(得分:2)

这应该这样做。

$GroupName = 'test';
$Adsi = [adsi]'WinNT://localhost';
$Adsi.Delete('group', $GroupName);

要从本地安全组中删除域组,请参阅以下代码:

function Remove-DomainGroupFromLocalGroup {
    [CmdletBinding()]
    param (
          [Parameter(Mandatory = $true)]
          [string] $LocalGroupName
        , [Parameter(Mandatory = $true)]
          [string] $DomainGroupName
    )
    begin {
        Add-Type -AssemblyName System.DirectoryServices.AccountManagement;
    }
    process {
        $LocalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Machine);
        $DomainContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain);

        $GroupPrincipal = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($LocalContext, [System.DirectoryServices.AccountManagement.IdentityType]::Name, $GroupName);
        $GroupToRemove = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($DomainContext, [System.DirectoryServices.AccountManagement.IdentityType]::Name, $Remove);

        if ($GroupToRemove) {
            $GroupPrincipal.Members.Remove($GroupToRemove);
            $GroupPrincipal.Save();
        }
    }
}

Remove-DomainGroupFromLocalGroup -LocalGroupName Administrators -DomainGroupName TestGroup;