获取脚本块中的所有远程变量

Get All Remote Variables in Script Block

有没有办法获取脚本块中所有远程变量的列表?

考虑以下几点:

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

在 $block 内部,是否有任何方法可以使用 $using: scoped 变量获取可用列表?

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

不产生 $x 作为可用变量

简短的回答是:你不能。

远端对变量一无所知。它们被序列化,然后嵌入反序列化代码和序列化的文字 XML。

如果您是编写脚本块的人,那么我建议您将每个 $Using: 变量分配给脚本块内的局部变量:

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

我在我的博客上写了关于在 DSC 脚本资源中使用它的更详细的解释 how $Using: is implemented