在PowerShell中管道到ForEach-Object

N3c*_*RiL 4 powershell foreach pipe

我正在写一篇关于我正在写的PowerShell脚本的地方.

基本上我要做的是让它通过目录进行递归,仅包含.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
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我运行脚本时,它要求我为脚本的ForEach部分提供参数 - 这让我得出结论:命令没有按照它应该的方式进行管道,或者我只是一个白痴而不是使用命令正确.

CB.*_*CB. 6

删除enterforeach-object:

$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   }
Run Code Online (Sandbox Code Playgroud)

你的代码中有一个拼写错误:

**    Get-ChildItem =path  **
Run Code Online (Sandbox Code Playgroud)


MrK*_*ins 5

这可能是因为 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
    }
Run Code Online (Sandbox Code Playgroud)