0

I runing the following simple powershell command on a remote server. However I need to pass a variable to the NET LOCALGROUP command:

$serverName = "SCO32"
$groupName = "SCO33_Local_Admins"
$Session = New-PSSession -ComputerName $serverName 

Invoke-Command -Session $Session -ScriptBlock {

$args[1]
$args[0]

net localgroup administrators domainname\$args[1] /ADD

} -ArgumentList $serverName, $groupName

The arguments are passing correctly as is the remote connection, it just doesn't seem to be able to execute the command because it's trying to use the $args[1] as a literal and not domainname\SCO33_Local_Admins

Thanks in advance.

3
  • Why not just use this script that already does exactly what you want to do? Commented Sep 5, 2014 at 16:13
  • @TheMadTechnician - thanks for the link, but this is part of something bigger, and I want to learn at the same time. Thanks. Commented Sep 5, 2014 at 16:21
  • I recommend using ADSI. Commented Sep 5, 2014 at 16:48

2 Answers 2

2
$servername = 'sv1'

In v2:

Invoke-Command -Session $Session -ScriptBlock { 
   param($servername, $group)
  net localgroup administrators domainname\$servername /ADD 
} -ArgumentList $serverName, $groupName

Or in v3

Invoke-Command -Session $Session -ScriptBlock { 
  net localgroup administrators domainname\${using:servername} /ADD 
}

Or:

Invoke-Command -Session $Session -ScriptBlock {
  net localgroup administrators domainname\$($args[1]) /ADD 
} -ArgumentList $serverName, $groupName
Sign up to request clarification or add additional context in comments.

Comments

0

Just like in a function or in a script you can assign parameters to a scriptblock. While using the automatic $args may not work for you, you can do this:

$serverName = "SCO32"
$groupName = "SCO33_Local_Admins"
$Session = New-PSSession -ComputerName $serverName 

Invoke-Command -Session $Session -ScriptBlock {
Param($SrvName,$GrpName)
net localgroup administrators domainname\$GrpName /ADD

} -ArgumentList $serverName, $groupName

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.