0
0
PowerShellscripting~5 mins

String comparison (-like, -match) in PowerShell

Choose your learning style9 modes available
Introduction

We use string comparison to check if text matches a pattern or contains certain characters. It helps us find or filter text easily.

Checking if a file name matches a pattern like '*.txt' before processing it.
Finding if a user input contains a specific word or phrase.
Filtering a list of names to find those starting with a certain letter.
Validating if a string follows a pattern like an email format.
Searching logs for lines that include certain keywords.
Syntax
PowerShell
$string -like <pattern>
$string -match <regex_pattern>

-like uses simple wildcard patterns like * and ?.

-match uses regular expressions for more powerful pattern matching.

Examples
Checks if the string ends with '.txt' using wildcard.
PowerShell
'hello.txt' -like '*.txt'
Checks if the string contains one or more digits using regex.
PowerShell
'hello123' -match '\d+'
Checks if the string starts with 'Power'.
PowerShell
'PowerShell' -like 'Power*'
Checks if the string exactly matches 'abc' followed by three digits.
PowerShell
'abc123' -match '^abc\d{3}$'
Sample Program

This script checks if a file name ends with '.txt' using -like. Then it checks if user input contains at least three digits using -match.

PowerShell
$fileName = 'report2024.txt'
if ($fileName -like '*.txt') {
    Write-Output "File '$fileName' is a text file."
} else {
    Write-Output "File '$fileName' is not a text file."
}

$userInput = 'Order123'
if ($userInput -match '\d{3}') {
    Write-Output "Input '$userInput' contains a 3-digit number."
} else {
    Write-Output "Input '$userInput' does not contain a 3-digit number."
}
OutputSuccess
Important Notes

-like is case-insensitive by default.

-match is also case-insensitive unless you use -cmatch for case-sensitive matching.

Use * in -like to match any characters, and ? to match a single character.

Summary

-like uses simple wildcards for easy pattern matching.

-match uses regular expressions for advanced matching.

Both help check if text fits a pattern or contains certain parts.