v_b
v_b

Reputation: 225

PowerShell: How can I delete a security group on a server?

How can I delete a Windows security group on a server using PowerShell scripting?

I have a task to delete all the old user groups, and would like to automate the process to save time.

Upvotes: 1

Views: 848

Answers (1)

user189198
user189198

Reputation:

This should do it.

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

To delete a domain group from a local security group, see the following code:

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;

Upvotes: 2

Related Questions