Matching a string against a list of predefined strings
Published on: 4th Dec 2019
Updated on: 16th Jan 2022
Explanation
To match an input string against a single pattern, you may use the -LIKE
operator just like SQL SELECT statement.
if ($my_string -like "*helo*") {
# do something here
}
Whereas to match an input string against a list of predefined strings, we use -MATCH
parameter. To show you how this works, we wrote a function that will check whether the input string is matching the weekday in the predefined format.
Our weekday format:
"_" + "first 3 character of weekday text"
So, our function will look like this (you may copy the script below into a ps1 file and execute it):
# returns true if the weekday param is matching the predefined file name convention.
function Is-weekday() {
param (
[string]$wd
)
if ($wd -match "_mon|_tue|_wed|_thu|_fri|_sat|_sun") {
return $true
}
return $false
}
# To test if it works, run the following line:
$weekday = "_wed"
Is-weekday $weekday
# result on screen: True
# Let's say we remove the underscore symbol from $weekday, we will get False as the result.
$weekday = "wed"
Is-weekday $weekday# result on screen: False
Jump to #POWERSHELL blog
Author
Lau Hon Wan, software developer.