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,group

Now 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

Rating 4.00 out of 5
[?]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Spam Protection by WP-SpamFree