I wish to use Invoke-Command passing environment variables from the calling machine to the server where Invoke-Command is being executed.
I want this to work:
Invoke-Command -ComputerName MyServer-ScriptBlock {
$env:VAR=$using:env:USERNAME
Write-Host $env:VAR
}
But the output for this command is empty. If I do not use the $using scope modifier, and just assign the variable directly I get the expected output ("VAR").
Invoke-Command -ComputerName MyServer -ScriptBlock {
$env:VAR="VAR"
Write-Host $env:VAR
}
So, can I use $using with environment variables? If not, is there an easy way to pass environment variables over to the remote computer where Invoke-Command is running?
One option would be to assign the environment variable to a standard variable before invoking:
$username = $env:USERNAME
Invoke-Command -ComputerName MyServer-ScriptBlock {
$env:VAR=$using:userName
Write-Host $env:VAR
}
Note that assigning environment variables like this ($env:VAR=<value>
) won't persist once your session ends. Use the Environment.SetEnvironmentVariable() method to do that.