在PowerShell中管道到ForEach-Object

时间:2013-01-24 14:32:44

标签: 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
    }

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

2 个答案:

答案 0 :(得分:6)

删除enter后的foreach-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   }

您的代码中存在拼写错误:

**    Get-ChildItem =path  **

答案 1 :(得分:4)

这可能是因为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
    }