【问题标题】:no receive-job results for gci when -path is a variable当 -path 是变量时,gci 没有接收作业结果
【发布时间】:2013-02-16 03:41:34
【问题描述】:

这不返回任何内容:

$x = "C:\temp"
Start-Job -ScriptBlock {get-childItem -path $x} | Wait-Job | Receive-job

但是提供不带变量的路径参数,像这样......

Start-Job -ScriptBlock {get-childItem -path C:\temp} | Wait-Job | Receive-job

...返回该临时文件夹的内容,在本例中为 durrr.txt。这是在 Windows Server 2008R2 SP1 上,Powershell $host.version 输出如下:

Major  Minor  Build  Revision
-----  -----  -----  --------
3      0      -1     -1

怀疑 Powershell 的 v3,我尝试将 Windows 7 SP1 桌面从 v2 更新到 v3,但没有运气重现问题。在升级后的桌面上,$host.version 输出现在与上述匹配。

发生了什么事?

编辑/发生了什么?

被破坏的工作似乎等同于

Start-Job -ScriptBlock {get-childItem -path $null} | Wait-Job | Receive-job

所以 gci 返回了后台作业当前目录的结果,Documents 文件夹恰好是空的。

【问题讨论】:

    标签: powershell powershell-3.0 get-childitem powershell-jobs


    【解决方案1】:

    您需要将参数传递给脚本块

    $x = "C:\temp"
    Start-Job -ScriptBlock {get-childItem -path $args[0]} -argumentlist $x  | Wait-Job | Receive-job
    

    在 powershell V3 中你可以这样做:

    $x = "C:\windows"
    Start-Job -ScriptBlock {get-childItem -path $using:x} | Wait-Job | Receive-job
    

    【讨论】:

    • 哈利路亚,谢谢。但是为什么在 Win7 和 2008R2 上会有不同的行为呢?
    • 您的代码在 xp、7、2008、2008 r2 上的 powershell v2.0/v3.0 中也不起作用。在 sciptblock 中传递变量的唯一方法是使用 argumentlist 参数。在 v3 中,我认为您可以使用 -path $using:x 并且它可以工作。
    • 我问题的前两行确实在 Win7 上返回结果。我会阅读脚本块参数。
    • @noam 更准确地尝试 ook,你会发现结果不是你的目录 c:\temp。在我的 7 框中返回 %env:userprofile\documents 的目录 ...
    • 哦。我尝试对自己投反对票,但谢天谢地,这是不允许的。
    猜你喜欢
    • 2023-03-21
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多