Using Variables in Remote PowerShell Sessions
Learn why local variables don't work in remote PowerShell sessions, as well as how to make them work.
June 14, 2014
For more technical explainers on PowerShell, read our updated 2021 report: PowerShell 101: A Technical Explainer for IT Pros.
Q: I'm trying to invoke commands on a remote server in PowerShell, but any variables I try to use are failing. What can I do?
A: PowerShell variables are great for storing information that's available within the PowerShell session. For example:
$message = "Message to John"write-host $message
would output the text contained in the $message variable with no problem. Now consider running the same command on a remote machine:
$message = "Message to John"Invoke-Command -ComputerName savdalhv20 -ScriptBlock {write-host $message}
Nothing shows in the output. The reason for this is that Invoke-Command creates a new PowerShell session on the remote machine that doesn't have the variables you defined locally available and therefore contains no data.
If you want to use variables in a remote session, such as with Invoke-Command, you need to pass those variables as parameters to the script block that will be used with Invoke-Command and then the actual value as an argument. For example:
$message = "Message to John" $ScriptBlockContent = { param ($MessageToWrite) Write-Host $MessageToWrite }Invoke-Command -ComputerName savdalhv20 -ScriptBlock $ScriptBlockContent -ArgumentList $message
This now works; the text in the message is output to the screen. This is because the code being run remotely via Invoke-Command is writing a variable, $MessageToWrite, which is expected as a parameter when used and is populated with the value of $message via the -ArgumentList. Therefore, when you want to use variables that are defined locally, you must pass them as parameters to the remote session.
About the Author
You May Also Like