Managing Local Groups through PowerShell
When managing Local Groups through PowerShell, we can use the [ADSI] type adapter.
Starting off, We have to connect to the Local Group that we want to modify.
PS > $ComputerName = $env:COMPUTERNAME PS > $Group = "Administrators" PS > $LocalGroup = [adsi]"WinNT://$computerName/$Group,group" PS > $LocalGroup distinguishedName : Path : WinNT://Computer01/Administrators,groupNow that we’re connected to the Local Group, we can start of by adding a user. First let’s add a Local User.
PS > $Domain = "powershell"
PS > $UserName = "nigo"
PS > $LocalGroup.Add("WinNT://$Domain/$userName")
This adds the Domain user powershell\nigo to the local Administrators Group. If we instead want to add a Local User, we just replace the Domain Name with the Local COmputer Name.
PS > $ComputerName = $env:COMPUTERNAME
PS > $LocalGroup.Add("WinNT://$ComputerName/$userName")
And if we want to remove a User from a local Group, we use the Remove() method.
PS > $Domain = "powershell"
PS > $UserName = "nigo"
PS > $LocalGroup.Remove("WinNT://$Domain/$userName")
Here’s a script that automates these tasks.
Click here to download the script.
Here are some examples on running the script.
PS > Set-LocalGroup.ps1 -UserName nigo -Add PS > Set-LocalGroup.ps1 -UserName nigo -Remove PS > Set-LocalGroup.ps1 -UserName nigo -Group "Guests" -Domain powershell -Add PS > Set-LocalGroup.ps1 -help
[?]
