Jeff
Jeff

Reputation: 36573

Get All Remote Variables in Script Block

Is there a way to get a list of all remote variables in a script block?

Consider the following:

$x = 1
$block = { Write-Host $using:x }
Invoke-Command -Session (New-PSSession) -ScriptBlock $block

Inside of $block, is there any way of getting a list of available $using: scoped variables?

$x = 1
$block = { Get-Variable }
Invoke-Command -Session (New-PSSession) -ScriptBlock $block

Does not yield $x as an available variable

Upvotes: 1

Views: 389

Answers (1)

briantist
briantist

Reputation: 47792

The short answer is: you can't.

The remote side doesn't know anything about the variables. They get serialized and then the deserialization code and the literal serialized XML is embedded.

If you're the one writing the script bock, then I recommend you just assign each $Using: variable to a local variable inside the scriptblock:

$block = {
    $x = $Using:x
    $y = $Using:y
}

I wrote a more detailed explanation of how $Using: is implemented on my blog regarding using it in DSC Script resources.

Upvotes: 1

Related Questions