PowerShell Script to Check if String Contains Substring
-like operator with wildcards like '*substring*' or the .Contains() method to check if a string contains a substring in PowerShell, for example: $string -like '*substring*' or $string.Contains('substring').Examples
How to Think About It
Algorithm
Code
$string = 'Hello World' $substring = 'World' if ($string -like "*${substring}*") { Write-Output 'True' } else { Write-Output 'False' }
Dry Run
Let's trace the example where $string = 'Hello World' and $substring = 'World' through the code
Assign variables
$string = 'Hello World', $substring = 'World'
Check if $string contains $substring
Evaluate if 'Hello World' -like '*World*' which is True
Output result
Print 'True'
| Step | Expression | Result |
|---|---|---|
| 2 | 'Hello World' -like '*World*' | True |
Why This Works
Step 1: Using -like operator
The -like operator checks if the string matches a pattern with wildcards, where * means any characters before or after the substring.
Step 2: Using .Contains() method
The .Contains() method returns True if the substring is found anywhere inside the string, otherwise False.
Alternative Approaches
$string = 'Hello World' $substring = 'World' if ($string.Contains($substring)) { Write-Output 'True' } else { Write-Output 'False' }
$string = 'Hello World' $substring = 'World' if ($string -match [regex]::Escape($substring)) { Write-Output 'True' } else { Write-Output 'False' }
Complexity: O(n) time, O(1) space
Time Complexity
Checking if a substring exists requires scanning the main string, which takes linear time proportional to the string length.
Space Complexity
No extra significant memory is needed; the check is done in-place with constant space.
Which Approach is Fastest?
The .Contains() method is generally faster and clearer for exact substring checks, while -like is simpler for wildcard patterns.
| Approach | Time | Space | Best For |
|---|---|---|---|
| -like with wildcards | O(n) | O(1) | Simple pattern matching with wildcards |
| .Contains() method | O(n) | O(1) | Exact substring presence, case-sensitive |
| -match with regex | O(n) | O(1) | Complex pattern matching with regex |
-like '*substring*' for simple wildcard checks or .Contains() for exact substring presence.* with -like causes the check to fail unless the string exactly matches.