How to use PowerShell “Contains” – A Quick Guide!

The Contains method in PowerShell can be used to check if a specified string or character exists within a string, and the PowerShell operator Contains allows you to check if a collection of objects, such as an array, contains a specific value. It returns a Boolean value, either $true if the string or character is found, or $false if it is not found. In this comprehensive guide, I will cover everything you need to know about PowerShell contains, including how to use it with arrays, if statements, where-object, case-insensitive searches, wildcards, regular expressions, and much more. I’ll also walk through real-world examples so you can see how to apply contains logic to validate input, search logs, and more in PowerShell scripts.

How to Use the PowerShell “Contains” Function in String?

The PowerShell contains function allows you to check if a string contains a specific substring. This can be useful for finding specific text in a file or checking if a string contains a certain word or phrase. Run the following command to use the PowerShell “Contains” function:

"Hello world".Contains("world")

In this example, we are checking if the string “Hello world” contains the substring “world”, and it returns “True”.

PowerShell Contains with If Statements

The Contains operator can be used in conditional statements, such as if statements, to check if a collection contains a specific value and take action based on the result. Here is an example of using the Contains operator in an if statement:

$string = "Hello, World!"
if ($string.Contains("World")) {
    Write-Output "The string contains the word 'World'"
} else {
    Write-Output "The string does not contain the word 'World'"
}

In this example, the Contains method will return $true because the string “Hello, World!” contains the word “World”.

The contains method is case-sensitive by default! So, the “Hello world”.Contains(“WORLD”) returns False, as the case differs. To perform a case-insensitive check, you can convert and make sure both the string and substring to the same case using ToLower() or ToUpper() methods. E.g

"Hello World".ToUpper().Contains("WORLD")
PowerShell String Contains

Using Contains Operator with Arrays

The -contains operator allows you to check if a collection contains a specified value. This works with arrays, lists, and other collections. You can also use the -Contains Operator to check if an object is contained in an array or collection.

The basic syntax is:

$collection -contains $value

This will return True if $value exists in $collection. For example:

#Array separated by commas
$array = "apple", "banana", "mango"

#Check if the array contains a string
if ($array -Contains "banana") {
    Write-Output "The array contains the string 'banana'"
} 
else {
    Write-Output "The array does not contain the string 'banana'"
}

In this example, the -Contains operator will return $true because the string “banana” is contained in the array string collection.

powershell contains

Also, The Contains operator does not use strict equality comparison, meaning that it does not check if the value is exactly equal to the value in the collection. For example,

$Array = 1, 2, 3.0, 4, 5
$result = $Array -Contains 3

Write-Output $result

Would return True as the $arrary containing the value 3.0, as the values are equal. You can use it for validating user inputs as well. Here is how:

#Set Valid values
$ValidColors = "Blue", "Red", "Green"

#Get the User Input
$color = Read-Host 'Enter color'

#Check if the entered value is valid using Contains operator
if ($validValues -contains $color) {
  "Valid color: $color"
} else {
  "Invalid color entered."
}

How to Use the Contains Operator with a Collection?

Let’s take a practical example to check if the services collection has a specific service on the computer.

#Get All Services - Expand Name
$Services = Get-Service | Select -ExpandProperty Name

#Check the Services Collection contains "Themes"
$services -contains "Themes"

This will return True if the ‘Themes’ service exists on the system. Please note, we have extracted the Name property from collection and checking a specific service. Here is another example to check for a specific object in a collection:

# Get all processes
$Processes = Get-Process

# Get just one process
$Process = $Processes | Select -First 1

# Check the collection
$Processes -contains $Process

In this context, the contains operator checks if the right-hand side of the operator is equal to any of the element of the collection in the left.

PowerShell Contains vs. Notcontains

The notcontains operator is the opposite of the contains operator. Instead of returning $true if the substring is found, it returns $false. The syntax for the notcontains operator is as follows:

$string1 -notcontains $string2

For example, let’s say that we have the same two strings:

$string1 = "The quick brown fox"
$string2 = "lazy"
$string1 -notcontains $string2

PowerShell will return $true, because the substring “lazy” is not contained within the string “The quick brown fox”.

The -notcontains can be used to negate the result of the Contains operator. For example:

#array
$Array = 1, 2, 3, 4, 5

#Checks if an array not contains a value
$Result = $Array -NotContains 5

Write-Output $Result

This would return False, as the array contains the given value: 5.

Case-sensitive Matching with Contains Operator

By default, -contains does a case-insensitive match. If you want to perform a case-sensitive search, use the -CContains operator. E.g. In the below example, the -CContains operator checks whether the test value exists in the collection considering its case:

#Array
$Fruits = "apple", "banana", "mango"

#Check if array contains a string
$Fruits -CContains "Banana"

This returns False, as the case for “banana” and “Banana” is not the same. (However, $Fruits -contains “Banana” return $True). So, It’s a good idea to convert the element of the string values into lowercase or uppercase.

The “IN” operator vs. Contains in PowerShell

The -in operator checks if the value exists in an array (Whereas the Contains operator checks if an array contains a given value):

#array
$Array = 1, 2, 3, 4, 5

#Checks if a value exists in the Array 
$Result = 4 -in $Array

Write-Output $Result

Similarly, the -NotIn operator checks if the value is not in a collection of values. E.g., “5 -Notin 1,2,3” returns $True.

I hope this helps give you a basic understanding of how to use the Contains method and operator in PowerShell.

PowerShell Contains with Where-Object

You can also use the contains method with where-object to filter objects based on whether they contain a specific substring. For example, let’s say that we have the following array of strings:

$array = @("The quick brown fox", "Jumped over the lazy dog", "Hello world")

If we want to filter this array to only include strings that contain the substring “quick”, we can use where-object like this:

$array | Where-Object { $_.Contains("quick") }

PowerShell will return an array that only contains the string “The quick brown fox”. Here is another real-world example:

# Get the Last 100 Events from Event Log
$Logs = Get-EventLog -LogName Application -Newest 100

# Filter Logs where the message contains Error
$ErrorLogs = $Logs | Where-Object {$_.Message.Contains("error")}

This filters the last 100 System event logs for any containing the word ‘error’.

Can I Use Contains operator with Wildcard and Regular Expressions?

The -contains operator is primarily designed for collections, not direct string comparisons. For strings, you’d use -like or -match. The Contains operator doesn’t support wildcards or regex, but PowerShell offers alternative operators for these functionalities. Unlike the Contains() function, The -Contains operator doesn’t do substring comparisons, and the match must be on a complete string (or object)!

Wildcards with -like Operator

PowerShell’s -like operator (and its friend: NotLike) allows for string comparisons using wildcards. The most commonly used wildcard is the asterisk *, which represents any sequence of characters.

$string = "Microsoft PowerShell is powerful"
$string -like "*powerful" # Returns $true

More on How to use the Like Operator in PowerShell?

Regular Expressions with -match Operator

While wildcards offer simple pattern matching, regular expressions (regex) provide more advanced and precise string matching. In PowerShell, the -match operator is employed to use regex.

$text = "The code is 123"
$text -match "\b\d{3}\b" # Returns $true

In summary, It’s important to differentiate between these operators:

  • -Contains: Checks if a collection has a specific element. It doesn’t work directly for string patterns.
  • -like: Allows string comparison using wildcards, providing a simple pattern-matching mechanism.
  • -match: Enables string comparison using regular expressions, offering advanced pattern recognition.

Always remember to use the right operator for the task – while -contains is fantastic for collections, -like or the -match is more suitable for string checks. Here is my other article on: PowerShell Match Operator

Conclusion

In summary, the PowerShell contains operator or method is a useful tool in PowerShell for checking if a collection of objects, such as an array or a string, contains a specific value. You can use its simple syntax in a variety of situations to automate tasks and boost your work efficiency. In this article, we have discussed the PowerShell contains function to check if a string contains a specific substring. We have also learned through some examples how to use this function.

I hope this guide provides a solid overview of how to leverage PowerShell’s contains functionality and operators for any beginner scripts. Let me know if you have any other questions!

Can you use the contains operator with Multiple values in PowerShell?

The contains operator is designed to check if a single value exists within a collection. However, You can use the ForEach loops to achieve it. Here is an example:
$Names = @('Alice', 'Bob', 'Charlie', 'David', 'Eva')
$namesToCheck = @('Bob', 'Eva', 'Frank')
$namesToCheck | ForEach-Object {
if ($names -contains $_) {
"$_ exists in the array."
} else {
"$_ does not exist in the array."
}
}

How do I check if a string contains a specific word?

In PowerShell, to check if a string contains a specific word or substring, you can use the -like operator combined with wildcards. For example:
$String = "I love PowerShell for automation!"
$String -like "PowerShell"

How do you check if a file contains a string in PowerShell?

To check if a file contains a specific string in PowerShell, you can use the Select-String cmdlet. Here’s an example of how to do it:
#Check if the file contains the string
if ((Get-Content -Path "C:\Logs\AppLog.txt") | Select-String -Pattern "Error") {
Write-Output "The file contains the string."
} else {
Write-Output "The file does not contain the string"
}

What is the difference between contains and like in PowerShell?

In PowerShell, the “contains” operator is used to check if a collection (like an array) contains a specific element, while the “like” operator is used for pattern matching. E.g.,
$colors = @('Red', 'Blue', 'Green')
$result = $colors -contains 'Blue' # Returns $true

$name = "PowerShell"
$result = $name -like "Power*" # Returns $true

How do you check if a string contains specific characters in PowerShell?

To check if a string contains specific characters in PowerShell, you can use the -match operator along with a regular expression pattern. Here’s an example:
"exampledef" -match "[abc]"
This checks if the string contains any of the characters a, b, or c. You can also use the -Like operator for wildcard search. E.g.,
"exampleabcdef" -like "abc"

How do you check if a property exists in object PowerShell?

To check if a property exists in an object in PowerShell, you can use the Get-Member cmdlet. Here’s an example:
$object | Get-Member -MemberType Property -Name "PropertyName"

How can I get files where the name contains a specific substring or pattern?

You can use the PowerShell Get-ChildItem cmdlet with the -Filter parameter to search for files that contain a specific substring or pattern in their name. For example, if you want to find all files in a directory that contain the word “example” in their name, you can use the following command: Get-ChildItem -Path “C:\Path\To\Directory” -Filter “example“. This will return a list of all files that have “example” anywhere in their name.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *