Steve
Steve

Reputation: 229

Add Current User To Admin Group

I'm trying to get the current user and add them to the Administrator Group. So far I'm able to get the current user and pass them to the Admin add, but I'm not sure how to call it with Admin credentials in order to actually add them.

$user = [Environment]::Username
$group = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/administrators,group")
$group.add("WinNT://$env:USERDOMAIN/$User,user")

Any help would be appreciated.

Upvotes: 2

Views: 7750

Answers (3)

Greg Bray
Greg Bray

Reputation: 15697

This might not work for the current user, but for a generic user or group you can use Powershell Remoting (WinRM) and the Invoke-Command and the net.exe program to add users as administrators to multiple computers:

icm -ScriptBlock {& "$env:SystemRoot\system32\net.exe" localgroup Administrators /add AccountName} -ComputerName server1,server2,server3

where AccountName is an AD User or Group and Server1,Server2,Server3 is a list of computers you want to run the script block on. This won't work for the current user since you have to be an Administrator to use WinRM, but it helps when you need to add another user or group as admin to a server.

If you don't have WinRM enabled, you can use PSEXEC to enable it remotely

psexec -s \Server1 cmd /c "winrm quickconfig -quiet"

Upvotes: 0

Steve
Steve

Reputation: 229

Here is the working solution:

$Cred = Get-Credential ("$env:COMPUTERNAME\Administrator")
$User = $env:USERNAME
$Domain = $env:USERDOMAIN
Invoke-Command -Computername localhost -Cred $Cred -ScriptBlock {
    param ($User, $Domain, $ComputerName)
    $Group = [ADSI]("WinNT://$ComputerName/Administrators,Group")
    $Group.add("WinNT://$Domain/$User,user")
} -ArgumentList $User, $Domain, $ENV:COMPUTERNAME

Upvotes: 3

BartekB
BartekB

Reputation: 8650

I'm not sure if that's the best way to do it, because to use ADSI with alternate creds - you need to send them in plain text:

$Local = New-Object -TypeName ADSI -ArgumentList @(
    "WinNT://$env:COMPUTERNAME/Administrators,group",
    $AdminUser,
    $AdminPass                           
)

$Local.Add("WinNT://$env:USERDOMAIN/$env:USERNAME")

Username usually takes form of domain\user (or $env:ComputerName\User).

Wouldn't it be better to do it other way around? Check from user account who is logged on and add this account? There few ways to get there (including tricks like checking owner of explorer.exe process).

HTH Bartek

Upvotes: 0

Related Questions