【问题标题】:Piping to ForEach-Object in PowerShell [closed]在 PowerShell 中管道到 ForEach-Object [关闭]
【发布时间】:2013-01-08 08:24:06
【问题描述】:

我试图让它通过一个目录递归,并且只包含.pdf 文件。然后返回最近修改的 3 个.pdf,并将它们的每个(完整)文件名粘贴到它们各自的变量中。

这是我目前的代码 -

$Directory="C:\PDFs"
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object 
    {
        Write-Host -FilePath $_.fullname
    }

但是,当我运行脚本时,它要求我为脚本的 ForEach 部分提供参数 - 这让我得出结论,要么命令没有按照应有的方式进行管道传输,要么命令不是正确使用命令。

【问题讨论】:

  • FYI mods 这个页面是谷歌热门,它解决了我的问题。我无法想象这个问题过于本地化了

标签: powershell foreach pipe


【解决方案1】:

去掉foreach-object后面的enter

$Directory="C:\PDFs"
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object {
        Write-Host -FilePath $_.fullname   }

您的代码中有错字:

**    Get-ChildItem =path  **

【讨论】:

    【解决方案2】:

    这可能是因为您的 ForEach-Object 脚本块位于新行上。在 PowerShell 中,您需要使用反引号字符 (`) 来告诉 PowerShell 命令继续到下一行。试试这个:

    $Directory="C:\PDFs"
        Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object `
        {
            Write-Host -FilePath $_.fullname
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-06
      • 2014-02-13
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多