简体   繁体   中英

PowerShell Conditional Efficiency: -match vs. -like

I have a simple Powershell script that collects Exchange message tracking results using a few filters and then returns items with '*SPAM*' in the subject. To do so, I take an array of Microsoft.Exchange.Management.TransportLogSearchTasks.MessageTrackingEvent objects and pipe it to a 'where' that checks the MessageSubject property of each entry.

I found that when I use the following for comparing the MessageSubject property, the code takes an extremely long time (hours) to complete for ~70,000 records:

($_.messagesubject -like '`*SPAM`*')

However when I use the following, the completion time is in seconds:

($_.messagesubject -match [regex]'^\\*SPAM\\*.*$')

I'm getting in over my head trying to determine the specific reasons the former takes so much longer to process. Don't both methods need to loop over the same number of objects? Is the difference in character-by-character comparisons (for -like) vs. a compiled regex? (for -match)

Are you sure that switching operators is the only thing that changes between versions? According to the following tests, performance of operators is not an issue. Moreover, the regex cast is the longest one. I also believe that the like pattern you use is wrong, you need to escape the asterisks as they are special wildcard characters (see $sb4).

PS> $msg = "just a sample spam message for testing"

PS> $sb1 = { 1..70000 | foreach {$msg -match [regex]'^\*SPAM\*.*$' } }
PS> $sb2 = { 1..70000 | foreach {$msg -match 'spam'} }
PS> $sb3 = { 1..70000 | foreach {$msg -like "*spam*" } }
PS> $sb4 = { 1..70000 | foreach {$msg -like "`*spam`*" } }    

PS> (measure-command $sb1).TotalSeconds
8.1869412

PS> (measure-command $sb2).TotalSeconds
6.7244995

PS> (measure-command $sb3).TotalSeconds
7.9287195

PS> (measure-command $sb4).TotalSeconds
6.9678701

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM