Coding Ref

How to use String Contains in PowerShell

How to use String Contains in PowerShell

To check if a string contains a specific substring in PowerShell, you can use the -Contains operator.

This operator allows you to check if a string contains a given substring, and returns $true if it does, or $false if it does not.

Examples

Here is an example of how to use the -Contains operator in PowerShell:

$myString = "Hello world"

if ($myString -Contains "world") {
    Write-Host "The string contains the substring."
} else {
    Write-Host "The string does not contain the substring."
}

In this example, the if statement uses the -Contains operator to check if the $myString variable contains the substring "world".

If it does, the code inside the if block will be executed, and a message will be output to the screen. If it does not, the code inside the else block will be executed, and a different message will be output to the screen.

You can also use the -Contains operator in a script to check if a string contains a substring and take a specific action based on the result.

For example, the following code checks if a string contains the substring "world", and outputs a message if it does:

$myString = "Hello world"

if ($myString -Contains "world") {
Write-Host "The string contains the substring 'world'."
}

Conclusion

To check if a string contains a specific substring in PowerShell, you can use the -Contains operator.

You'll also like

Related tutorials curated for you

    How to use Start-Job in PowerShell

    How to rename a file in PowerShell

    How to use -Contains in PowerShell

    What is null in PowerShell?

    How to make a directory in PowerShell

    Everything about certificates in PowerShell

    How to move items in PowerShell

    How to use ErrorAction in PowerShell

    How to copy and paste into PowerShell

    How to get the string length of a variable in PowerShell

    What is `ls` for PowerShell?

    How to restart a service in PowerShell