PowerShell: A Simple Formula for “If Like”


You can use the following syntax in PowerShell to use “if like” logic to check if a string contains a specific substring:

if ($my_string -like "*this_string*") {
echo "String contains substring"
} else {
echo "String does not contain substring"
}

This particular example checks if the string variable named my_string contains “this_string” anywhere in it.

If it does, then String contains substring will be returned.

If it does not, then String does not contain substring will be returned.

The following example shows how to use this syntax in practice.

Example: How to Use “If Like” in PowerShell

Suppose we have a variable named my_string that contains the following string:

  • “The Mavs are the best basketball team”

Suppose that we would like to check if this string contains the substring “Mavericks” anywhere in it.

We can use the following syntax to do so:

$my_string = "The Mavs are the best basketball team"

if ($my_string -like "*Mavericks*") {
echo "String contains substring"
} else {
echo "String does not contain substring"
}

The following screenshot shows how to use this syntax in practice:

PowerShell if like

The if statement returns “String does not contain substring” because the string indeed does not contain the substring “Mavericks” anywhere in it.

Suppose we search for the substring “avs” instead:

The if statement returns “String contains substring” because the string does indeed contain the substring “avs” in it.

Also note that the -like operator is not case-sensitive.

For example, suppose we search for the substring “AVS” instead:

The if statement returns “String contains substring” because the string does indeed contain the substring “AVS” (case-insensitive) in it.

Note that in these examples we used asterisks ( * ) to check if a substring with any characters on either side of it existed in another string.

You can also use the following syntax if you would instead like to check if a string begins or ends with a specific substring:

  • *avs: Check if a string ends with “avs”
  • avs*: Check if a string begins with “avs”

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply