Mochael_DLite
Mochael_DLite

Reputation: 187

Select-String is taking too long. How can I optimize it

I am really trying to speed this script up. I have a directory with about 17k files in it:

$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 "[email protected]" -To [email protected] -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
           }

Upvotes: 0

Views: 1303

Answers (1)

Chris N
Chris N

Reputation: 7489

If Select-String is taking a long time in the script above, try only doing it once. Also, I see that you check the count and if nothing is going on, you delete that CSV you made. So howabout you count it first, and then only make it if you need to.

...

$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...
}

Upvotes: 1

Related Questions