Select-String花费的时间太长了。我该如何优化它

时间:2016-01-20 19:33:14

标签: powershell select-string

我真的想加快这个剧本的速度。我有一个包含大约17k文件的目录:

$date= Get-Date -Format yyyyMMdd
$dir= "C:\test\$date"
$path=Get-ChildItem -Path $dir -Recurse
$pattern = "<RESULT>FAILED</RESULT>"
$submitted = (select-string -path $path -pattern $pattern | measure-object).Count
select-string -path $path -pattern $pattern | select Path,Filename,Line | Export-Csv -Path "D:\Failed.csv"

if($submitted -eq 0) {
    Remove-Item "D:\Failed.csv" -recurse
}
else
           {
    Send-MailMessage -From "noreply@email.com" -To users@email.com -Subject "Failed Report" -Body "Attached are the failed files.  This is for the last 3 hours.  There may be files that were already reported." -Attachments "D:\Failed.csv" -SmtpServer 0.0.0.0
    Remove-Item "D:\Failed.csv" -recurse
           }

1 个答案:

答案 0 :(得分:1)

如果Select-String在上面的脚本中花了很长时间,请尝试只执行一次。此外,我看到您检查计数,如果没有进行任何操作,则删除您创建的CSV。所以你要先计算它,然后只在你需要的时候才能计算出来。

...

$submitted = select-string -path $path -pattern $pattern
...
if(($submitted | Measure-Object).Count -gt 0){
   ...make the csv using the $submitted variable as the source...
   ...send the csv...
   ...delete the csv...
}