【问题标题】:Does Invoke-Command run in the current scope, or a child scope, when run locally?在本地运行时,Invoke-Command 是在当前范围内运行还是在子范围内运行?
【发布时间】:2019-07-11 16:31:01
【问题描述】:

我在comment on another post 中获悉:

至于Invoke-Command:不幸的是,文档不正确:by 默认情况下,本地调用发生在子范围内,但您可以选择 与-NoNewScope 进行相同范围的执行。 – mklement0

但是,根据help documentation(强调添加):

您还可以在本地计算机上使用 Invoke-Command 来评估或运行 脚本块中的字符串作为命令。 Windows PowerShell 转换 脚本块到一个命令并立即运行该命令在 当前作用域,而不仅仅是在命令行中回显字符串。

这似乎按预期工作:

PS C:\> $TestVar = 99
PS C:\> Invoke-Command { Get-Variable TestVar }

Name                           Value
----                           -----
TestVar                        99

如果文档有误,我预计这会导致 Invoke-Command 无法使用该变量。文档到底是正确的吗?

【问题讨论】:

  • 这样看。第二个 $a 不变:invoke-command { $a = 1 } ; $a
  • @js2010 我喜欢这样。这是显示问题的一种非常简洁的方式。

标签: powershell scope


【解决方案1】:

文档提供了混合信息,问题中引用的部分肯定已过时/不正确。

提供正确信息的帮助部分位于-NoNewScope 下方,其中指出:

表示这个cmdlet在当前运行指定的命令 范围。默认情况下,Invoke-Command 在自己的范围内运行命令。

该参数只对当前运行的命令有效 session,即同时省略 ComputerName 和 Session 的命令 参数。

此参数是在 Windows PowerShell 3.0 中引入的。

以下显示来自-NoNewScope 的范围信息是正确的(用编号的范围表示):

$TestVar = 99
Invoke-Command { Get-Variable TestVar -Scope 0 } #Scope 0, current scope
Invoke-Command { Get-Variable TestVar -Scope 1 } #Scope 1, parent scope
Invoke-Command { Get-Variable TestVar -Scope 0 } -NoNewScope #Scope 0, current scope

第一个命令的结果将返回一个错误,指出找不到变量:

PS C:\> Invoke-Command { Get-Variable TestVar -Scope 0 } #Scope 0, current scope
Get-Variable : Cannot find a variable with the name 'TestVar'.

其他命令将按预期返回变量信息。但是,正如另一篇文章的评论中提到的,-NoNewScope 必须用于明确告诉Invoke-Command 使用当前范围,否则它将默认在子范围中运行。

问题中的命令起作用的唯一原因是,变量默认可用于子作用域,并且由于未使用 -ComputerName-Session 参数,因此不需要声明作用域。

截至 2019 年 8 月 21 日,documentation update request 已完成。问题中提到的问题部分的新版本现在为:

You can also use `Invoke-Command` on a local computer to a script block as a command.
PowerShell runs the script block immediately in a child scope of the current scope.

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2021-07-30
    • 1970-01-01
    • 2011-11-12
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    相关资源
    最近更新 更多