- 1 year ago
PowerShell - send variable via Invoke-Command
In PowerShell, you can use the Invoke-Command
cmdlet to run a script block or a command on a remote computer. To send a variable from your local computer to the remote session created by Invoke-Command
, you can use the -ArgumentList
parameter.
Here's an example of how to use Invoke-Command
to send a variable to a remote session:
powershell# Define the variable you want to send to the remote session
$MyVariable = "Hello, this is a variable value!"
# Specify the remote computer name or IP address
$ComputerName = "RemoteComputerName"
# Use Invoke-Command to run a script block or command on the remote computer
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
param($RemoteVariable) # Define a parameter to receive the variable from the local session
Write-Host "Received variable: $RemoteVariable"
} -ArgumentList $MyVariable
In this example, we define the $MyVariable
variable with the data we want to send to the remote session. We then use Invoke-Command
to run a script block on the remote computer specified in the $ComputerName
variable. Inside the script block, we define a parameter called $RemoteVariable
to receive the variable from the local session. The -ArgumentList
parameter is used to pass the value of $MyVariable
to the remote session.
When you run the Invoke-Command
command, it will establish a remote session to the specified computer, run the script block, and pass the value of $MyVariable
to the $RemoteVariable
parameter. The script block will then display the received variable value using Write-Host
.
Note that Invoke-Command
requires administrative privileges on the remote computer, and the WinRM service must be enabled on the remote computer for this to work. Additionally, make sure you have proper permissions and network access to the remote computer.