PowerShell -Contains Operator and .Contains() Method Explained

Photo of author

By Victor Ashiedu

Published

Do you want to compare an object against a collection or substring against a string in PowerShell? Then, you need the PowerShell -contains operator or contains() method.

Overview

PowerShell -Contains Operator And Contains() Method: Overview

In PowerShell, an operator is a language element that you can use in a command or expression. OK, that came out too technical!

But just stay with me, it will get clearer as you read on, I promise.

The phrase “language element” that I used above refers to things like -eq, -match, and of course, -contains. In PowerShell, you use these “language elements” in commands of scripts.

In essence, you use PowerShell operators to manipulate values.

Moving on, there are about nine categories of PowerShell “language elements” (or operators). One of those categories is the Comparison Operators.

If you guessed that the -contains operator belongs to this category, you would be right! The -contains operator compares an object against a collection of objects.

Apart from the -contains operator, there is also the .Contains() Method. The .Contains() method compares a substring against a string.

To learn more about PowerShell strings and substrings, read my article How To Extract A PowerShell Substring From A String.
If you’re still struggling to follow my explanation so far, don’t give up yet. It will get clearer when we get to the examples section. However, do not skip anything as you need all the information to eventually find the examples helpful.

Syntax

The Syntax Of The PowerShell -Contains Operator And The .Contains() Method

The syntax of the -Contains Operator is…

<Collection> -contains <Test-object>

<Collection> represents the collection of objects that contains elements of the <Test-object>. On the other hand, the <Test-object> is the object you wish to compare against the full collection.

However, if you want to use the Contains() Method, here is the syntax.

String.Contains(string value)

String represents the “bigger information box” while string value is the substring you’re comparing against the String.

When you run the -Contains Operator or the .Contains() Method, it returns a $TRUE or $FALSE.

The -Contains Operator is case-insensitive. Another important piece of information about the -contains operator is that it is not limited to strings.
On the contrary, the .Contains() Method is only limited to strings and it is case-sensitive by default. More on the applications of all these in the examples section (next section).

Examples

In this guide so far, you have read a quick overview of PowerShell Contains (operator and Method). Additionally, I have explained the syntaxes of the operator and the Method.

This section features a collection of script-ready examples. Dive in!

1. A Basic Illustration

I decided to start this examples section with a very simple example. I have a textile shown in the screenshot below in the path Get-Content D:\report\.

PowerShell -Contains Operator And .Contains() Method Examples

In this first example, I want to use the -Contains Operator or the .Contains() Method to check whether the file contains the string “Short description”.

As you can see from the screenshot, the file contains this string.

First, I will run the Get-Content command to extract the content of the file. Then, save the contents of the file in a variable I have called $file.

Here is the command…

$file = Get-Content D:\report\about_operators.txt

Next, I want to use the PowerShell -Contains operator to check if the string exists in the file. Before I run the next command, I want you to take another look at the syntax of the -Contains operator.

<Collection> -contains <Test-object>

In the example I am about to show you, can you guess what represents the <Collection>? It is the information I saved in the $file variable.

Similarly, the <Test-object> is the string “Short description” that I want to check whether it exists in the information saved in the $file variable.

In other words, does the file D:\report\about_operators.txt contain the information “Short description”?

Here is the -Contains operator command that will give us the answer…

$file -contains ("Short description")

And the answer is…TRUE!

Now, let me show you how to get the same answer with the .Contains() Method. Before I show you the command, here is a reminder of the syntax…

String.Contains(string value)

And now the actual PowerShell .Contains() Method command…

$file.Contains("Short description")

Once again, the answer is…TRUE!

PowerShell -Contains Operator And .Contains() Method Examples

2. Perform Case Sensitive and Insensitive Comparison

If you recollect, in the syntax section of this guide, I explained that the -Contains operator is case-insensitive. To make it case-sensitive, include “C” before “Contains”.

So, the case-sensitive version of -Contains is -CContains. To avoid the assumption that all my readers understand what I mean by case-sensitive and case-insensitive, let me quickly explain.

In the last example, I compared the string “Short description”. Case-sensitive means that I must specify the string exactly as it is written – Short description – including the capital “S”.

On the contrary, case-insensitive means that it doesn’t matter how I present the string. In other words, for a case-insensitive scenario, Short description is the same as short Description.

Now that we have covered all the basics, let me show you how this works in a real-life scripting situation.

To illustrate, I will continue with the first example. Lets me start with the -contains operator. Remember that it is case-insensitive.

So, it doesn’t matter how I represent the information in the <Test-object>. See the syntax below…

<Collection> -contains <Test-object>

So, it means that as far as the PowerShell -Contains operator is concerned, these two commands will produce the same result.

$file -contains ("Short description")
$file -contains ("short Description")

And they did!

How To Perform Case Sensitive And Insensitive Comparison With PowerShell -Contains Operator And .Contains() Method

However, if I want to run the command and force case sensitivity, I will run the commands below. One of the commands will return False.

$file -Ccontains ("Short description")
$file -Ccontains ("short Description")

The second command produces a False! Why? – continue reading after the screenshot.

If you recollect, the information in the text file has “Short description”. But, in my second command, I used “short Description”.

Now, let’s look at how the PowerShell .Contains() Method handles case sensitivity and insensitivity.

I mentioned in the syntax section of this guide that the .Contains() Method is case-sensitive by default. So, the command below will return false…

$file.Contains("short Description")
How To Perform Case Sensitive And Insensitive Comparison With PowerShell -Contains Operator And .Contains() Method

3. Check if an Array of Objects Contains an Item in Another Array

To demonstrate this example, I will start by creating two PowerShell arrays.

$ArrayList1 = @("Document", "FileSystem", "D:\PS-Tutorial")
$ArrayList2 = @("Document", "FileSystem", "C:\Users\victo\Documents")

As you can see from the two array lists, two objects – Document and FileSystem – are common to both. In this example, I want to check if “C:\Users\victo\Documents” found in $ArrayList2 is in $ArrayList1.

The first step is to note that “C:\Users\victo\Documents” is the second object in $ArrayList2. So it is represented by…

$ArrayList2[2]

Next, I will use PowerShell -contains operator to check if the object returned in the above command – C:\Users\victo\Documents – is in $ArrayList1.

Here is the command…

$ArrayList1 -contains ($ArrayList2[2])

As expected, the result is False…

How To Use PowerShell To Check If An Array Of Objects Contains An Item In Another Array

To confirm that the above command works, let’s now use it to check for an object we know exists in both arrays – Document. From the command I used to create $ArrayList2, we know that the object Document is in position 0.

$ArrayList2 = @("Document", "FileSystem", "C:\Users\victo\Documents")

So, to return that object, I will use the command below:

$ArrayList2[0]

Finally, I will use PowerShell -contains operator to check if the object returned in the above command – Document – is in $ArrayList1.

Here is the command…

$ArrayList1 -contains ($ArrayList2[0])

The command returned True because as we know the object Document is in $ArrayList1!

4. Use PowerShell -Contains vs -Like Operators

The major difference between PowerShell -Contains vs -Like operators is that one accepts wildcards but the other does not. Specifically, the -Contains operator does not accept wildcards but the -Like operator does.

To demonstrate this, let’s continue with the information saved in the $file variable. To refresh your mind, here is the command that saved the content of a file to the $file variable.

$file = Get-Content D:\report\about_operators.txt

In a previous example, I used the command below to check if the content of the file contains the string, “Short description”.

$file -contains ("Short description")

The above command works. However, if I try to use a wildcard, it will return false.

$file -contains ("Short*")

In the last command, I use the asterisks (*) wildcard. Here are the results of the last and previous commands…

How To Use PowerShell -Contains vs -Like Operators

The command that does not use the wildcard retired True but the command that used it returned False. We know that the file contains the string, so it means that the PowerShell -contains operator does not accept wildcards.

However, if I use the -Like operator with a wildcard, it returned True. Here is the command and the screenshot of the result…

($file | out-string) -like "*Short*"
How To Use PowerShell -Contains vs -Like Operators
In the last command, I piped $file to the out-string command to convert $file from an array to a string. Otherwise, the -Like operator would have returned the string “Short description” instead of True.

5. Use .Contains() Method to Check if Any Two or Three Substrings Exist in a String

To demonstrate this example, I will recall my $ArrayList1 command.

$ArrayList1 = @("Document", "FileSystem", "D:\PS-Tutorial")

I want to check if any two substrings are on the array list. If any of the substrings exists in the array list (string), PowerShell will return True, otherwise, it returns False.

$ArrayList1.Contains("Document") -or $ArrayList1.Contains("Bin")

The operator that does the magic is the logical operator, -or. Logical -or is used to check if “this or that” is true. If any of the items are true, the result is true.

So, in the last command, I used the PowerShell .contains Method to check if the array list (string) contains the substrings Document and Bin. As seen in the screenshot below, the result is True.

How To Use PowerShell .Contains() Method To Check If Any Two Or Three Substrings Exist In A String

Why is the result True even if, as we know the subscribing, Bin is NOT in the strings saved in $ArrayList1? Here is the command that created $ArrayList1.

$ArrayList1 = @("Document", "FileSystem", "D:\PS-Tutorial")

The answer is that Logical -or returns True when one of the items is true. However, if I replaced the Logical -or with Logical -and operator, the result will be False…

The reason the last command returned False is that for the Logical -and operator to return True, both items MUST return True.

6. Check if a Strings Contains the Square Bracket

While I was researching this topic, I found this question on the VistaForums.

The person that posted the question wants to use PowerShell to check if the string “[abc]” contains the square bracket ([).

The person tried this command…

"[abc]" -contains "["

But, it returned false…

How To Use PowerShell Contains To Find The Square Bracket In A String

Apparently, the solution (courtesy of one contributor) is to use the PowerShell .Contains () method, rather than the operator.

Here is the command that does the magic…

# first, assign the string to a variable
$string = "[abc]"
# then, call the .contains() method
$string.Contains('[')

This time around, we get the right result, True!

7. Count the Number of Occurrences a Substring Appears in a String

I mentioned that I found the last example in a forum. Well, it appears that you get a lot of weird questions in forums!

I also found this example in another forum, Stackoverflow.com. In this question, the question contributor wanted to know how to count the number of occurrences a particular substring appears in a string.

Before, you proceed, I like to add a bit of disclaimer: this example has nothing to do with PowerShell Contains, but I felt it is relevant.

OK, here it is. To replicate the Stackoverflow.com question, I want to count the number of times the string “For example” appears in the text file shown in the screenshot below…

The first step is to get the content of the file. Then, to make it easier to manipulate, I’ll save the content of the file in a variable I call $file.

$file = Get-Content D:\report\about_Methods.txt

Since the Get-Content cmdlet retries the content of the file into an array, I will need to convert it to a string. To do this, I will pipe Get-Content to Out-String.

$file = Get-Content D:\report\about_Methods.txt | Out-String

Then, I will use the Select-String command to return all matches of the string, “For example”…

$file | Select-String "For example" -AllMatches

The command returns all matches of the string found. I know it is not looking pretty but stay with me…

The last command has a Method called Match. To filter out all the irrelevant strings above, use this method…

($file | Select-String "For example" -AllMatches).Matches

The above command now returns the actual substring, “For example”. But, there is one more task left – to count the number of occurrences.

This time, I will use the Count Method…

($file | Select-String "For example" -AllMatches).Matches.Count

Finally, we have our answer. The substring, “For example” occurred 8 times in that text file!

Frequently Asked Questions

1. How do I use contains in PowerShell?

You can use PowerShell Contains in two ways.

First, you can use the Contains operator. Here is the syntax of a contains operator:

-contains

Secondly, you can use Contains method. See the syntax of the contains method below:

String.Contains(string value)

2. How do you check if a string contains a text in PowerShell?

You can use either the Contains operator or the Contains method to check if a string contains a text in PowerShell.

For example, to check if the string, “I love PowerShell”, “PowerShell is easy to learn”, “I can teach you PowerShell”, contains the text “PowerShell is easy to learn”, I’ll use the commands below:

“I love PowerShell”, “PowerShell is easy to learn”, “I can teach you PowerShell” -contains “PowerShell is easy to learn”

or

( “I love PowerShell”, “PowerShell is easy to learn”, “I can teach you PowerShell”).contains(“PowerShell is easy to learn”)

Both commands return True. In the first command, I used Contains operator. Meanwhile, in the second command, I used the Contains method

3. What are PowerShell operators?

In PowerShell, an operator tells PowerShell to perform a specific operation and return results. Operators are used to manipulate values.

There are 8 major categories of PowerShell Operators. Some of the most popular categories are Arithmetic Operators like “+, -“.

To read more about operators, enter the command “Get-Help about_Operators” (without the quotes) in a PowerShell console.

4. How do I compare strings in PowerShell?

You can use one of the comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare strings (and values) and test conditions in PowerShell.

5. What is a variable in PowerShell?

Microsoft’s official definition of a variable is “a unit of memory in which values are stored”, but that doesn’t really mean much to a newbie.

Here is my lay-mans definition. A variable in PowerShell is used to save values to make them easy to manipulate. In PowerShell, a variable is characterized by text strings that begin with a dollar sign ($).

For example, $b, $process.

Conclusion

At first glance, the PowerShell -Contains Operator and .Contains() Method looks complex and daunting. However, when you understand their syntaxes, you can pretty much use them to solve complex problems.

The reason you need to know both the -contains operator and .contains() method is that serve different purposes. In some instances, you can use either of them.

However, in some scripting scenarios, you can only get one of them to work. So, I hope I have been able to get you started in your journey to using the PowerShell -Contains Operator and .Contains() Method?

If you found my explanations easy to follow and useful, click on “Yes” beside the “Was this page helpful” question below. You may also express your thoughts and opinions by using the “Leave a Comment” form at the bottom of this page.

Finally, you can improve your PowerShell skills by reading more articles on our Windows PowerShell Explained page. Alternatively, you can take a look at our  Windows PowerShell How-To Guides.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment

Send this to a friend