如果找到文件则停止 get-Childitem

Sha*_*iss 1 windows directory powershell get-childitem

我有这个代码:

    $Paths = 'C:\' , 'P:\' , "\\fril01\ufr$\$env:username"

    $torEXE = Get-childitem -path $paths -recurse -Exclude $ExcludePaths -erroraction 'silentlycontinue'  | where-object {$_.name -eq "Tor.exe"}

    if ($torEXE.Exists) {$answer = 1}

Run Code Online (Sandbox Code Playgroud)

检查文件 tor.exe,但正如您所看到的,此检查可能需要一些时间。检查可能会在前几秒找到 tor.exe,但会继续检查所有路径。我希望它在找到 tor.exe 后立即停止,而不是继续搜索它。如何做呢?

Mat*_*sen 5

坚持|Select-Object -First $N在管道的末尾,使其在第一个对象到达后停止执行$NSelect-Object

$torEXE = Get-ChildItem -Path $paths -Recurse -Exclude $ExcludePaths -ErrorAction 'silentlycontinue'  | Where-Object {$_.Name -eq "Tor.exe"} |Select -First 1
Run Code Online (Sandbox Code Playgroud)

  • 它不会,“Select-Object -First 1”将[导致管道停止](/sf/ask/4255319141/ )在找到第一个“tor.exe”后突然出现,这要归功于[管道命令处理的本质](/sf/ask/3396569081/并行)在 PowerShell 中 (3认同)