Search code examples
powershellpowershell-3.0powershell-4.0

How do I pass a local variable to remote PowerShell Script


Let me brief out what all methods I tried.

Here is the Start_TestTalk.ps1 script

$RN = $env:RName $TestV = "Local_Variable" Write-Host $TestV Write-Host $RName Write-Host $RN Write-Host $env:RName

I've declared the below variables

$Name="myname" $CPU= 100

First Method:

PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Start_TestTalk.ps1 " -RName $args[0] -RCPU $args[1]}-argumentlist $Name,$CPU Local_Variable

Second Method

PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Start_TestTalk.ps1 " -RName $using:Name -RCPU $using:CPU} Local_Variable

Third Method

PS C:\Users\Administrator> Invoke-Command -Session $s -Scriptblock{ Param($Name, $CPU) & "C:\Users\Administrator\Desktop \Start_TestTalk.ps1" -RName $Name -RCPU $CPU}-argumentlist $Name ,$CPU Local_Variable

All the above three methods just prints the 'Local_Variable' which is local to the remote machine and doesn't print the variable that I pass from my local machine(here $Name).


Solution

  • I figured out the way on how this feature works with the help of a Senior Architect here in our company. The variables sent from the local(source machine) are not actually made local on the remote machine and these just get dumped as values on the remote machine and not as variables(you can't use variables). A simple example on how the above script which I had mentioned works

    Start_TestTalk.ps1 script

    $RN = $args[0] $CPU= $args[1] Write-Host $RN Write-Host $CPU

    Now use the same old Invoke Command with slight changes removing the variables earlier used to hold the values from local machine

    Invoking the remote script using argument list

    I've declared the below variables $Name="myname" $CPU= 100 PS C:\Users\Administrator\ Invoke-Command -Session $s -Scriptblock{ & "C:\Users\Administrator\Desktop\Start_TestTalk.ps1" $args[0] $args[1] }- argumentlist $Name,$CPU myname 100

    Now you see that you get the required output on the remote machine, so it conveys that the values are directly getting dumped and not with the variables and hence I was earlier not able to use those variables on the remote machine.