0
0
PowerShellscripting~5 mins

match operator in PowerShell

Choose your learning style9 modes available
Introduction
The match operator helps you find if a text contains a certain pattern. It makes searching easy and fast.
Checking if a file name has a specific extension.
Finding if a user input contains a keyword.
Searching logs for error messages.
Filtering a list of names to find those starting with a letter.
Syntax
PowerShell
$string -match $pattern
The operator returns True if the pattern is found, otherwise False.
Patterns use regular expressions, which are like special search rules.
Examples
Checks if 'Hello World' contains 'World'. Returns True.
PowerShell
'Hello World' -match 'World'
Checks if 'apple' starts with 'a'. Returns True.
PowerShell
'apple' -match '^a'
Checks if '123abc' contains one or more digits. Returns True.
PowerShell
'123abc' -match '\d+'
Sample Program
This script checks if the word 'fun' is in the text. It prints a message based on the result.
PowerShell
$text = 'PowerShell is fun'
if ($text -match 'fun') {
    Write-Output 'Pattern found!'
} else {
    Write-Output 'Pattern not found.'
}
OutputSuccess
Important Notes
The match operator is case-insensitive by default.
You can use parentheses to capture parts of the match in the automatic variable $matches.
To do a case-sensitive match, use -cmatch instead.
Summary
The match operator checks if text contains a pattern.
It returns True or False.
It uses regular expressions for flexible searching.