首页 > 解决方案 > 使用 Where-Object 打开文件

问题描述

我搜索一个文件,例如 hosts 文件:

cd c:\Windows\System32
gci -Recurse | ? {$_.Name -eq 'hosts'}

现在我想在 中打开文件notepad,所以我尝试了:

gci -Recurse | ? {$_.Name -eq 'hosts'} | notepad.exe $_.FullName

这个错误。有没有办法做到这一点,作为一个单线?

标签: powershell

解决方案


notepad.exe不接受管道输出输入

Get-ChildItem -Recurse -ErrorAction SilentlyContinue |
    Where-Object -FilterScript { $_.Name -eq 'hosts' } |
        Foreach-Object -Process { notepad.exe $_.FullName }

为此,我建议在 get-childitem 上使用 -Filter。它将大大提高脚本的性能。-@马特

Get-ChildItem -Filter Hosts -Recurse -ErrorAction SilentlyContinue |
    ForEach-Object -Process { notepad.exe $_.FullName }

推荐阅读