Remotely Add Users to the Local Admins Group with Powershell

I can't tell you how many times I have had to reach out and touch multiple servers to add a service account to one of the systems local groups. This can be a time consuming endeavor when you get above a few machines.

This post lists the code needed to add a user to the local administrators group of a remote system.

To use the script, change the following;

  • PATH_TO_SERVER_LIST, Change this to the path to the list of servers on which to add the user.
  • DOMAIN_NAME, Change to your domain name
  • USER_TO_ADD, Change to the domain user you want to add to the remote systems local administrators group.

That's all you need.

The script makes an ADSI connection to the server

$AdminGroup = [ADSI]"WinNT://$s/Administrators,group"

The script then loads the user AD object.

 $User = [ADSI]"WinNT://$DomainName/$UserName,user"

And finally the script attempts to add the user to the local administrators group.

Note that each of the commands is wrapped in a try/catch block which outputs an error indicating where the problem occurs.

$servers = gc "PATH_TO_SERVER_LIST"
$DomainName = "DOMAIN_NAME"
$UserName = "USER_TO_ADD"

foreach($s in $servers){
   $s
   try{ $AdminGroup = [ADSI]"WinNT://$s/Administrators,group" }
   catch{ write-warning "Failed to connect to [$s]" }
   try{ $User = [ADSI]"WinNT://$DomainName/$UserName,user" }
   catch{ write-warning "Failed to obtain record for [$DomainName] [$UserName]" }
   try{ $AdminGroup.Add($User.Path) }
   catch{ write-warning "Failed to add user [$DomainName\\$UserName] to [$s]" }
   }

Note: You can select the group by changing the word Administrators in the connection line to the group to which you want to add the user.

For example, to use the local users group instead of administrators, the line would be;

  • $AdminGroup = [ADSI]"WinNT://$s/Users,group"

Leave a Reply