PowerShell -match vs -like
I've never seen -match
test that much faster than -like
, if at all. Normally I see -like
at about the same or better speed.
But I never rely on one test instance, I usually run through about 10K reps of each.
If your're looking for performance, always prefer string methods if they'll meet the requirements:
$string = '123abc' (measure-command {for ($i=0;$i -lt 1e5;$i++) {$string.contains('3ab')}}).totalmilliseconds(measure-command {for ($i=0;$i -lt 1e5;$i++) {$string -like '*3ab*'}}).totalmilliseconds(measure-command {for ($i=0;$i -lt 1e5;$i++) {$string -match '3ab'}}).totalmilliseconds265.3494586.424646.4878
See this explanation from Differences Between -Like
and -Match
In a nutshell, if you are thinking, 'I am probably going to need a wildcard to find this item', then start with
-Like
. However, if you are pretty sure of most of the letters in the word that you are looking for, then you are better off experimenting with-Match
.Here is a more technical distinction:
-Match
is a regular expression, whereas-Like
is just a wildcard comparison, a subset of-Match
.
So, whenever you are not sure what character classes, i.e. digits, letters, punctuation, etc., can there be inside, when you just want to match any character, you should be using -Like
with its wildcards.
When you know there must be a digit at the start followed with 1+ sequences of a colon followed with alphanumeric characters up to the end of the string, use -Match
with its powerful regular expressions.
You should prefer -like
when your comparator string is a dos-style filename wildcard. If you have a cmdlet that is designed to look like a "standard" windows command line application, then you can expect file name parameters to include dos-style wildcards.
You might have a grep-like cmdlet that takes a regex and a list of files. I can imagine it being used like this:
> yourMagicGrepper "^Pa(tt).*rn" *.txt file.*
You would use -match
when working with the first parameter, and -like
for all other parameters.
In other words: it depends on your functional requirements.