Home ยป PowerShell ยป Check If Variable contains String in PowerShell

Check If Variable contains String in PowerShell

Using the -like and -match operators and the Contains method, you can check if variable contains string in PowerShell.

It is essential and often needed while working with a script to check if a variable contains a specific string or pattern which can be crucial in creating a conditional statement.

In this article, we will discuss how to use the Like, Match operators, and Contains() method to check if a variable contains a specific substring.

Using the -like Operator if Variable Contains String

The -like operator in PowerShell variable with wildcards can be used to compare strings and find if a variable contains a string.

$greetings = "Hello! Welcome to ShellGeek website." 
if($greetings -like "*Shell*" ) 
{ 
   Write-Host "The variable contains the word 'ShellGeek'."
} 

In the above PowerShell script, the variable $greetings stores the value of a string data type.

To check if a variable contains a specific substring, we used an if statement that uses an -like operator with wildcard characters *. If the condition evaluates to true, it will print the message within the if statement.

The output of the above script finds the substring within a variable and prints it on the console.

The variable contains the word 'ShellGeek'.

Using the -match Operator if Variable Contains String

The -match operator in PowerShell allows you to use a regular expression to find matching patterns.

$greetings = "Hello! Welcome to ShellGeek website."   

if($greetings -match "Shel[la]Gee[ke]" ) 
{
   Write-Host "The variable contains a variations of the word 'ShellGeek'."
}         

The above PowerShell script uses the -match operator with a regular expression to compare the strings and find pattern matching.

The output of the above script is:

The variable contains a variations of the word 'ShellGeek'.

Using the Contains method to Check if a Variable Contains Substring

Use the Contains() method to check if a variable contains the specified string.

$greetings = "Hello! Welcome to ShellGeek website."

if( $greetings.Contains("ShellGeek"))
{
  Write-Host "The variable contains the word 'ShellGeek'."
}

In the above PowerShell script, the Contains method takes a string as an input parameter to check within the variable.

The output of the above script is:

The variable contains the word 'ShellGeek'.

Conclusion

I hope the above article on how to check if a variable contains a string using the -like, -match operator, and Contains method is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.