Pass varaible by reference to Invoke-Command

I need to pass local variable to remote session by reference because variable needs to be modified, for example:

$Session = New-PSSession
$var = 0

Invoke-Command -Session $Session -ScriptBlock {
	param ([ref] $var)
	$var.Value = 5
} -ArgumentList ([ref] $var)

$var

I can’t use $using:var because that implies read-only, I get an error saying:

InvalidData: Cannot process argument transformation on parameter ‘var’. Reference type is expected in argument.

Is there a way to send variable by reference?

AFAIK, I Don’t think passing variables by reference is a possible option in remote executions, variables by reference is basically pointing to the address in memory rather than passing value directly. Here both systems are not sharing the same address space.

3 Likes

OK thank you, this makes sense.

Hi,

I don’t know why u would pass it by a reference. You can pass variable the following way…
$PassVar = Get-Process

-ScriptBlock {
$Using:PassVar
}

I do believe Matablaster’s intent was to alter the var on the remote system and have that change be reflected on the local system. Hence the “$Using:” scope would not help.