到PowerShell中ForEach对象的管道

到PowerShell中ForEach对象的管道,powershell,foreach,pipe,Powershell,Foreach,Pipe,我试图让它在目录中递归,并且只包含.pdf文件。然后返回3个最近修改的.pdf,并将每个文件名(完整)粘贴到各自的变量中 这是我到目前为止的代码- $Directory="C:\PDFs" Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object {

我试图让它在目录中递归,并且只包含
.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部分提供参数——这让我得出结论,要么命令没有按应有的方式进行管道传输,要么命令没有正确地使用该命令。

删除
ForEach对象之后的
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  **

这可能是因为ForEach对象的脚本块位于新行上。在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
    }

仅供参考mods这个页面是谷歌的热门,它解决了我的问题。我无法想象这个问题有什么地方过于本地化