【问题标题】:PowerShell Remoting $Using variable scopePowerShell远程处理$使用变量范围
【发布时间】:2014-09-19 17:36:09
【问题描述】:

我有文件夹 c:\test 我有三个文件:“file1”、“file2”、“file3”

以下脚本:

$remoteSession = New-PSSession -ComputerName localhost
$folder = "c:\test"
$exclude =@("c:\test\file1","c:\test\file2")

Invoke-Command -Session $remoteSession -ScriptBlock {    
    #$Using:exclude
    Get-ChildItem -Path $Using:folder -recurse | Where {$Using:exclude -notcontains $_.FullName}
}

Remove-PSSession $remoteSession 

给出结果:

但是,如果我取消注释“$Using:exclude”,我会得到结果:

突然排除列表开始正常工作

【问题讨论】:

  • 我得到:New-PSSession : [localhost] Beim Verbinden mit dem Remoteserver "localhost" ist folgender Fehler aufgetreten: Zugriff verweigert
  • 好的,我必须是Administrator 才能开始pssession。另一个问题:你在哪里取消注释,它已经被取消注释了。

标签: powershell powershell-3.0 powershell-remoting


【解决方案1】:

仅在 Where-Object cmdlet 中指定 $Using:exclude 不起作用,因为它位于嵌套的 scriptblock 中。

在您的情况下,Using:folder 有效,因为它是直接传递给Invoke-Command 的局部变量脚本块

但是“Using:exclude 被传递给Where-Object脚本块,它本身嵌套在Invoke-Command脚本块中。

$Using 允许将局部变量传递给仅一层深度的脚本块,而不是进一步嵌套的 脚本块。 此行为并非特定于 Where-Object 脚本块,任何具有获取脚本块参数的 cmdlet 在其位于 Invoke-Command 脚本块内时的行为都是如此。

很遗憾,我认为这种行为没有记录在案。

通过在Invoke-Command 脚本块 的开头取消注释$Using:exclude,您实际上是在远程会话中声明了变量$exclude。 因此,在这种情况下,$exclude 成为Invoke-Command scriptblock 内的局部变量,并且可以进一步传递到嵌套的Where-Object scriptblock

这就是为什么当您在 Invoke-Command 脚本块的开头取消注释 $Using:exclude 时它起作用的原因,这是 $Using 行为的解决方法。

有关此运行的官方帮助信息:

Get-Help about_remote_variables -Full

【讨论】:

  • 查看我对这篇文章的回答 :)
  • 在您的回答中,您“$using:”远程脚本块最外层范围内的两个变量,这允许将它们传递到 & 脚本块中。我认为@Mathieu 解释得很好。
  • 在我的情况下,我在取消注释$Using:exclude时得到所有三个文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2012-03-08
  • 2015-05-02
相关资源
最近更新 更多