What is the difference between –Match, -Like and –Contains Operator in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

All the above 3 operators (Match, Like, and Contains) mentioned are the comparison operator in PowerShell. Match and Like operators are almost similar operator only difference is the Wildcard character and the Contains operator is entirely different. We will see the example and understand how they work.

Example

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "PowerShell"
True
PS C:\WINDOWS\system32> "This is a PowerShell String" -Like "PowerShell"
False
PS C:\WINDOWS\system32> "This is a PowerShell String" -Contains "PowerShell"
False

If you see the output of the above example, the result is True only for the Match statement and reason is when you match the keyword in the string, it checks whether the keyword exists or not. It doesn’t matter the keyword you used is an individual keyword or connected word. The below statement is also true.

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "Shell"
True

But wildcard character (*) is not helpful for the Match operator.

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "*PowerShell*"
parsing "*PowerShell*" - Quantifier {x,y} following nothing.
At line:1 char:1
+ "This is a PowerShell String" -Match "*PowerShell*"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException

So Match condition doesn’t evaluate the Regex operator. In contrast, Like operator is used with the wildcard character(*).

PS C:\WINDOWS\system32> "This is a PowerShell String" -like "*PowerShell*"
True

So the wildcard plays a major role between the Match and Like operator. We can check the wildcard (*) use with the Contains operator.

PS C:\WINDOWS\system32> "This is a PowerShell String" -contains "*PowerShell*"
False

Contains operator also doesn’t work with the wildcard (*) character. It is an entirely different operator than Match and Like and works with the collection of objects (Array).

PS C:\WINDOWS\system32> "Apple","Dog","Carrot","Cat" -contains "dog"
True
raja
Published on 15-May-2020 16:34:57
Advertisements