How to use PowerShell "Contains" - A Quick Guide! (2024)

How to use PowerShell "Contains" - A Quick Guide! (1)

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 post, I will cover everything you need to know about PowerShell contains including using it with arrays, if statements, where-object, case-insensitive searches, wildcards, regular expressions, and more. I’ll also go through some real-world examples so you can see how to use contains logic to validate input, search logs, and more in your PowerShell scripts.

Table of contents

  • How to Use the PowerShell “Contains” Function in String?
  • PowerShell Contains with If Statements
  • How to use the Contains method for a case-insensitive search?
    • How do I check if a string contains any of multiple substrings?
  • Using Contains Operator with Arrays
  • How to Use the Contains Operator with a Collection?
  • PowerShell Contains vs. Notcontains
  • Case-sensitive Matching with Contains Operator
  • The “IN” operator vs. Contains in PowerShell
  • PowerShell Contains with Where-Object
  • Can I Use Contains Operator with Wildcard and Regular Expressions?
    • Wildcards with -like Operator
    • Regular Expressions with -match Operator
  • Conclusion

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:

# PowerShell if contains example$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”.

How to use the Contains method for a case-insensitive search?

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")

How do I check if a string contains any of multiple substrings?

Use a loop or array methods to check for multiple substrings.

$string = "Hello, World!"$substrings = @("Hello", "Universe")$containsAny = $falseforeach ($sub in $substrings) { if ($string.Contains($sub)) { $containsAny = $true break }}$containsAny

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 stringif ($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.

You can also use the Where-Object cmdlet with the Contains method to check if any element in an array of strings contains a specific substring.

$array = @("Apple", "Banana", "Cherry")$substring = "Ban"$array | Where-Object { $_.Contains($substring) }

Furthermore, 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,

# PowerShell array contains - example$Array = 1, 2, 3.0, 4, 5$result = $Array -Contains 3Write-Output $result

Would return True as the $arrary containing the value 3.0, as the values are equal. You can use it to validate 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 operatorif ($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 that we have extracted the name property from the collection and are 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 elements of the collection on 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 5Write-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 $ArrayWrite-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 short, the PowerShell contains operator or method, which is a handy tool for checking if a collection of objects, such as an array or a string, contains a specific value. Its simple syntax can be used in many situations to automate tasks and get more work done. In this post, we covered the PowerShell contains function for checking if a string contains a substring and went through some examples.

I hope this guide provides a solid overview of leveraging 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 checks whether a single value exists within a collection. However, you can use the ForEach loops to achieve this. 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 I check if a string contains only digits?

Use the -match operator with a regex pattern for digits only. For example:
$string = "12345"
$string -match "^\d+$"

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 files with “example” anywhere in their name.

How do I check if a string contains a digit?

Use the -match operator with a regex pattern for digits.
$string = "Hello123"
$string -match "\d"

How do I check if a string starts with a specific substring?

Use the StartsWith method of the string object.
$string = "Hello, World!"
$string.StartsWith("Hello")

Similarly, To check if a string ends with a specific substring, you can use the EndsWith() method.

How do I find the index of a substring within a string?

Use the IndexOf method of the string object.
$string = "Hello, World!"
$substring = "World"
$index = $string.IndexOf($substring)

What is the difference between the -like and Contains methods?

The -like operator uses wildcard pattern matching, whereas the Contains method checks for a specific substring.
$string -like "*World*"
# vs.
$string.Contains("World")

Related Posts

How to use PowerShell "Contains" - A Quick Guide! (2024)
Top Articles
13 Sinking Funds Categories You Need in Your Budget
How I increased my pageviews by 918% in one month | August 2018 Income Report
7 C's of Communication | The Effective Communication Checklist
Why Are Fuel Leaks A Problem Aceable
Noaa Charleston Wv
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Free Atm For Emerald Card Near Me
Flixtor The Meg
Horoscopes and Astrology by Yasmin Boland - Yahoo Lifestyle
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
Bloxburg Image Ids
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
Day Octopus | Hawaii Marine Life
Blue Ridge Now Mugshots Hendersonville Nc
Thotsbook Com
Amelia Bissoon Wedding
Enderal:Ausrüstung – Sureai
Craigslist Deming
Used Drum Kits Ebay
Conan Exiles Thrall Master Build: Best Attributes, Armor, Skills, More
Teenleaks Discord
Equibase | International Results
Gayla Glenn Harris County Texas Update
Pokemon Unbound Shiny Stone Location
Crossword Help - Find Missing Letters & Solve Clues
Craigs List Jonesboro Ar
Egusd Lunch Menu
Catchvideo Chrome Extension
Www.1Tamilmv.con
Flaky Fish Meat Rdr2
Att U Verse Outage Map
Truis Bank Near Me
Morlan Chevrolet Sikeston
Navigating change - the workplace of tomorrow - key takeaways
Roto-Rooter Plumbing and Drain Service hiring General Manager in Cincinnati Metropolitan Area | LinkedIn
Blue Beetle Movie Tickets and Showtimes Near Me | Regal
Babylon 2022 Showtimes Near Cinemark Downey And Xd
Nancy Pazelt Obituary
Easy Pigs in a Blanket Recipe - Emmandi's Kitchen
2700 Yen To Usd
About My Father Showtimes Near Amc Rockford 16
No Boundaries Pants For Men
Ds Cuts Saugus
56X40X25Cm
Enr 2100
Tommy Bahama Restaurant Bar & Store The Woodlands Menu
The Nikki Catsouras death - HERE the incredible photos | Horror Galore
Argus Leader Obits Today
Laura Houston Wbap
Diamond Spikes Worth Aj
Is Chanel West Coast Pregnant Due Date
Joe Bartosik Ms
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5918

Rating: 4.2 / 5 (43 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.