3

How do I pass a powershell argument to a non-powershell command?

 2 years ago
source link: https://www.codesd.com/item/how-do-i-pass-a-powershell-argument-to-a-non-powershell-command.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How do I pass a powershell argument to a non-powershell command?

advertisements

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.


$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
}

Invoke-Command -Session $Session -ScriptBlock {
  net localgroup administrators domainname\$($args[1]) /ADD
} -ArgumentList $serverName, $groupName

Tags powershell

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK