Page 1 of 1

Add a Domain User to the Local Administrators Group

Posted: Wed Jul 03, 2019 5:52 am
by bhnuser
Hello everybody,

i need your help with my snippet. I would like, as the title says, to add a domain user to the Administrators group on a local machine on the network. The problem is that I run the script with a normal user without admin rights. Is it possible to pass an Admin user to the script below to run it. The snippet will be added to a PowerShell project.

Code: Select all

$DomainUser = "SamAccountName"
$LocalGroup = "Administrators"
$Computer   = $env:computername
$Domain     = $env:userdomain

([ADSI]"WinNT://$Computer/$LocalGroup,group").psbase.Invoke("Add",([ADSI]"WinNT://$Domain/$DomainUser").path)

Re: Add a Domain User to the Local Administrators Group

Posted: Wed Jul 03, 2019 8:28 am
by jvierra
You will have to connect ADSI using the full type.
See: https://docs.microsoft.com/en-us/dotnet ... ationTypes_

Re: Add a Domain User to the Local Administrators Group

Posted: Wed Jul 03, 2019 11:42 pm
by bhnuser
Okay, I've read the article ready. But what about the syntax in PowerShell?

Re: Add a Domain User to the Local Administrators Group

Posted: Thu Jul 04, 2019 12:45 pm
by jvierra
To add a user to the local admin group on the current system (excluding DCs) -

Add-LocalGroupMember -Group Administrators -Member domain\userid

You will not be able to establish remote domain credentials if AD has not been configured to allow this. To do this as a domain admin use "RunAs" with domain credentials to start PowerShell.

Assuming that AD has been set up then use this to see how to connect with credentials.

[adsi]::New

Look at the constructor options and refer to the documentation for how to use them.

Re: Add a Domain User to the Local Administrators Group

Posted: Thu Jul 04, 2019 1:18 pm
by jvierra
Also be aware that you cannot remotely authenticate with domain credentials and add members to a group that are domain accounts.

Re: Add a Domain User to the Local Administrators Group

Posted: Wed Jul 10, 2019 10:54 pm
by bhnuser
Thank you for the help jvierra.
I build now a workaround and it works fine. Here is the snippet:

Code: Select all

$localAdminUser = "WinNT://$($env:USERDOMAIN)/$($selectedUserLocalAdmin.SamAccountName)"
Invoke-Command $ADSession -Scriptblock {
				param ([string]$t3 = $Computer,
					[string]$t4 = $username) ([ADSI]"WinNT://$t3/Administrators,group").add($t4)
			} -ArgumentList $selectedComputer.Name, $localAdminUser
It works, because i build build a session to our DomainController when i start the script. So i can use Invoke-Command with the session.