Массив подстановочных знаков powershell в предложении where

PowerShell Match Operator

In this article, we will explore the ins and outs of the PowerShell match operator, including the basics of using -match to search strings, matching different patterns like numbers, words, and special characters, How anchors, character classes, and quantifiers work, and how to work with match groups. We’ll also provide practical examples and tips for mastering this essential PowerShell operator. Let’s dive in and master regex pattern matching in PowerShell together!

Introduction to PowerShell Match Operator

The PowerShell -match operator is a powerful tool for pattern matching in PowerShell. With this operator, you can search for strings that match a particular pattern, making it easier to find the data you need. The -match operator uses regular expressions (regex) to define the pattern parameter you are searching for. The .Net Regular expressions (regex) provide a powerful way to match specific string patterns in PowerShell.

The Basics of Using the -match Operator in PowerShell

To fully understand the power of the PowerShell -match operator, it’s important to have a solid understanding of regex string patterns. A regex string pattern is a character sequence defining a search pattern. The pattern can include special characters and symbols that define the types of characters you are searching for. For example, the . character matches any single character, while the * character matches zero or more occurrences of the preceding character.

"string" -match "RegEx pattern"

In this example, string is the string you want to search, and pattern is the regex string pattern you want to match. The -match operator returns a Boolean value indicating whether the string matches the pattern. If the string matches the pattern, the value is True. If the string does not match the pattern, the value is False.

"Hello World" -match "Hello"

This would return $true because ‘Hello’ matches the string ‘Hello World’.

Case-Sensitive Match

By default, the -match operator is case-insensitive, meaning “WORLD” and “world” are considered the same. If you need case-sensitive matching, use the -cmatch operator.

This script returns $False.

Using Anchors to Match Position

By default, the -match operator will search anywhere in the string to find a match. You can use regex anchors to force a match at a specific position. For example, ^ matches the start of the string, while $ matches the end:

Start of String Anchor (^ Caret)

The ^ anchor forces a match at the start of the string:

'Hello World' -match '^Hello' # Returns $true
'Hello World' -match '^World' # Returns $false

End of String Anchor ($ Dollar Sign)

The $ anchor forces a match at the end of the string:

'Hello World' -match 'World$' # Returns $true 
'Hello World' -match 'Hello$' # Returns $false

Using anchors allows you to control where a match must occur in the string. How about the Start and End Anchors?

'Hello World' -match '^Hello World$' # Returns $true
'Hello World!' -match '^Hello World$' # Returns $false - Because it ends with !

This requires the entire string to match the regex pattern. Anchors let you control exactly where in the input string the match must occur. This provides more precision when using -match.

powershell match operator start with ends with anchors

Matching Multiple Patterns with the Pipe

"Hello" -match "hello|goodbye" # Returns $true

This will look for either ‘hello’ OR ‘goodbye’ in the string. In other words, This will match because ‘Hello’ contains the word ‘hello’ even though it does not contain ‘goodbye’. If you’re matching multiple groups of patterns, use parentheses for clearer grouping.

"I have apples and bananas" -match "(apple|orange) and (banana|grape)"
$matches[1]  # Returns "apple"
$matches[2]  # Returns "banana"

Here is a practical example: Let’s say you’re filtering files based on several extensions.

$Filename = "document.pdf"
if ($filename -match "\.(jpg|jpeg|png|pdf|docx)$") {
    Write-Output "File format is supported."
} else {
    Write-Output "File format is not supported."
}

If you want to ensure a string matches a specific file extension pattern, the above match string PowerShell technique can be used.

Using Character Classes in PowerShell Match

Regex character classes allow you to match different sets of characters:

  • \d – Integer or Decimal Digits (0-9)
  • \D – Matches any non-digits (E.g., matches “ab”, “cd”, etc. but not “12”)
  • \w – Alphanumeric word characters (a-z, A-Z, 0-9, _)
  • \W – matches non-word characters (non-alphanumeric “#$%” etc.)
  • . – Any character except newline
  • \s – Whitespace character
  • \S – Non-Whitespace character
'Hello 123 world' -match '\d' # Matches the 1
'Hello 123 world' -match '\w{3}' # Matches the Hel

Character classes are an easy way to match types of characters without having to enumerate every possibility. Let’s find IPv4 Addresses from the given text:

$text = '127.0.0.1 is localhost'

$text -match '(\d{1,3}\.){3}\d{1,3}'
$Matches[0] # Contains '127.0.0.1'

This locates IPv4 addresses using a regex pattern. Similarly, to extract numbers from a String, use:

"Price is INR.100" -match "(\d+)"
$matches[1] # Returns "100"

Matching Repeating Patterns with Quantifiers

You can use regex quantifiers to match repeating occurrences of a pattern:

  • * – Zero or more occurrences. a* matches “”, “a”, “aa” etc
  • + – One or more occurrences. a+ matches “a”, “aa” etc but not “”
  • ? – Zero or one occurrence. For example, it makes the preceding token optional. ab?c matches “ac” and “abc”
  • {n} – Exactly n occurrences – a{3} matches “aaa”.
  • {n,} – At least n occurrences – a{2,} matches “aa”, “aaa” etc
  • {n,m} – Between n and m occurrences – a{2,4} matches “aa”, “aaa”, “aaaa”
  • [] – Matches any character in the set. E.g., [abc] matches “a”, “b”, “c”
  • [^] – Matches any character NOT in the set. E.g., [^abc] matches any char except “a”, “b”, “c”
'Hellooo World' -match 'o+' # Matches ooo
'Hellooo World' -match '\w{3}' # Matches the Hel
'Hellooo World' -match '\w{3,5}' # Matches Hello

Quantifiers are useful for flexibly matching repeating content.

Retrieving Match Groups using the $Matches Variable

One of the most powerful features of the -match operator is the ability to work with match groups. Match groups allow you to extract specific parts of a matched string, making working with the data you find easier. This variable contains an array of all match groups for the most recent -match operation. Each array element corresponds to a match group, starting with index 1.

$PhoneNumber = "(123) 456-7890"
$PhoneNumber -match "\((\d{3})\)"
$matches[1]

When a match occurs, PowerShell populates the automatic $Matches variable with information about the matches:

'Hello World' -match '(\w+) (\w+)'
$Matches

This would return:

PS C:\Scripts>

Name                           Value
----                           -----
2                              World
1                              Hello
0                              Hello World

Parentheses in a regex pattern define “capture groups” that store matches. After a successful -match operation, PowerShell stores the result in the $matches variable, making it easier to retrieve matched groups.

'Hello World' -match '(\w+) (\w+)'
$Matches[1] # Stores 'Hello'
$Matches[2] # Stores 'World'

You can retrieve the content of these match groups by index from the $Matches variable.

Capture groups are very useful for extracting specific parts of a matched string. Here is another example:

"User: John, Age: 25" -match "User: (\w+), Age: (\d+)"

The $matches PowerShell array now will contain:

$matches[0]: User: John, Age: 25 
$matches[1]: "John"
$matches[2]: "25"
PowerShell $matches

Difference Between -match and -like Operators in PowerShell

While the -match operator is an essential tool for pattern matching in PowerShell, it is not the only operator available. Another commonly used operator is the -like operator. While both operators can be used for string matching, they work in different ways. The main difference between the -match and -like operators is that the -match operator performs a regex pattern match, while the -like operator performs a wildcard match. If you need to perform advanced pattern matching or extract specific data from strings, the -match operator with regular expressions is the way to go.

When deciding which operator to use, consider the complexity of the pattern you need to match. If you need to search for a complex pattern, the -match operator may be the better choice. The- like operator may be more appropriate if you need to search for a simple pattern.

While both are used for string comparisons:

  • -match: Uses regex patterns for detailed string matching.
  • -like: Uses wildcard patterns (* and ?) for simpler string comparisons.

Using the -match Operator for Pattern Matching in PowerShell

Let’s take a closer look at how to use the -match operator for pattern matching in PowerShell. As mentioned earlier, the -match operator uses regex string patterns to define the pattern you are searching for. To use the operator, you simply need to include it in your script or command.

$emailList = "example1@gmail.com", "example2@hotmail.in","example3@yahoo.com", "example4@hotmail.us"
$emailList -match ".*\.com"

In this example, the .* characters match any number of characters, and the \. character matches a literal period. The com characters match the literal string com. The result of this command is a list of all email addresses that end in .com.

Filtering with where-object and -match

The where-object match combo is a force multiplier in PowerShell. Here is an Example:

:/>  Эквалайзер для Windows 10: инструкция настройки штатными средствами системы Виндовс и обзор лучших сторонних программ

Suppose you have a list of files, and you want to filter out those that are JPEGs:

$files = "image1.png", "image2.jpeg", "image3.jpg"
$jpegFiles = $files | Where-Object { $_ -match "\.(jpeg|jpg)$" }

This highlights the potential of PowerShell where-Object and match operators.

Not Matching a Pattern (PowerShell not match)

If you want to check that a string does not match a pattern, use the -notmatch operator. Using -notmatch returns True if the string doesn’t match the pattern.

"Hello World" -notmatch "Universe"

This will return True.

Advanced Techniques for Matching Strings in PowerShell

While the basics of the -match operator are relatively simple, you can use several advanced techniques to improve your string-matching skills in PowerShell. These techniques include:

[regex]::Matches("A1 B2 C3", "\w\d") | ForEach-Object { $_.Value }

Using Special Characters

Regular expressions often use special characters (like . or *). Ensure these characters are escaped if they should be matched literally.

"Hello." -match "Hello\." # Returns $True because the dot is escaped

Here, we have used the \ (backslash) as an escape character to match “.”.

Practical Examples of Using the -match Operator in PowerShell

Let’s take a look at some practical examples of using the -match operator in PowerShell. These examples demonstrate real-world scenarios where -match and regex can extract and validate data in PowerShell scripts.

Example 1: Finding All Files With a Certain Extension

Here are some real-world examples of using -match and regex in PowerShell scripts:

Get-ChildItem -Path C:\ -Recurse | Where-Object { $_.Name -match "\.txt$" }

In this example, the Get-ChildItem command retrieves a list of all files in the C:\ directory and its subdirectories. The Where-Object command filters the list to include only files that end with the .txt extension.

$url = 'https://www.example.com/path1/path2'
if ($url -match '^(?<protocol>.+)://(?<domain>.+)/?(?<path>.+)?') {
  $Matches.protocol # https
  $Matches.domain # www.example.com
  $Matches.path # path1/path2
}
$HTML = @"
<html>
<head>
    <title>Basic HTML Page</title>
</head>
<body>
    <h1>Welcome to My Basic HTML Page</h1>
    <p>This is a basic HTML page.</p>
</body>
</html>
"@
#Define the Start and End Strings
$Start = "<title>"
$End= "</title>"

#Use the Match Operator to get the Text between $Start and $End
If($HTML -match "(?s)$start(.*?)$end")
{
    Write-host "Title:" $matches[1]
}
2023-09-21 10:00:01 INFO: User 'john.doe' logged in from 192.168.1.10
2023-09-21 10:10:35 WARN: Connection timeout from 192.168.1.11
2023-09-21 10:15:42 INFO: User 'jane.smith' logged in from 192.168.1.12
2023-09-21 10:35:23 ERROR: Disk space low on server name 'server01'
...
#Get the Log File Contents
$LogEntries = Get-Content -Path "C:\Logs\Applog.txt"

#Parse the Log File
$LoginEntries = $logEntries | Where-Object { $_ -match "INFO: User '(.+)' logged in from (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" }

#Extract the desired entries
$loginEntries | ForEach-Object {
    if ($_ -match "INFO: User '(.+)' logged in from (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") {
        $user = $matches[1]
        $ip = $matches[2]
        [PSCustomObject]@{
            Username = $user
            IPAddress = $ip
        }
    }
} | Format-Table -AutoSize

In this example, the Get-Content command retrieves the contents of a log file. The ForEach-Object command loops through each line of the log file and extracts the date, time, and message from each line using a match group. The result is a list of PowerShell objects containing the extracted data.

parse log file in powershell using regex match

Example 5: Email Validation

Here is how to check if an email is in a valid format using the -match operator and regex in PowerShell

$Email = "john.doe@example.com"

if ($email -match "^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$") {
  Write-Output "Valid email format"
}
else {
  Write-Output "Invalid email format" 
}

Let’s break down the regex pattern:

  • ^ and $ anchors match the start and end of the string
  • [\w-\.] matches alphanumeric, hyphens, and periods
  • + quantifier matches one or more of those characters
  • @ matches a literal @ symbol
  • ([\w-]+\.)+ matches the domain name part (alphanumeric and hyphens)
  • \w{2,} matches the top-level domain (at least 2 alphanumeric chars)

Example 6: Validating a password

$password = "P@ssw0rd"
if ($password -match "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&+=]).{8,}$") {
    Write-Output "Valid password."
} else {
    Write-Output "Invalid password."
}

In this example, we match a password pattern that requires at least one lowercase letter, one uppercase letter, one digit, one special character, and a minimum length of 8 characters. If the password matches the pattern, the -match operator will return $true, indicating a valid password.

Comparing the -match Operator with Other Matching Operators in PowerShell

PowerShell provides several operators for matching strings, each with its strengths and use cases. Let’s compare the -match operator with other popular matching operators and cmdlets in PowerShell.

  • -like: The -like and -notlike operators are used for simple wildcard matching. It supports wildcards such as * and ? to match patterns. However, it does not support the full power of regular expressions.
  • -eq: The -eq operator and -ne are used for exact string matching. It checks if two strings are exactly equal. It does not support pattern matching or wildcards.
  • -contains: The -contains operator checks if an array contains a specific element. It does not support pattern matching or wildcards.
  • -in: The -in operator checks if an array contains a value. It does not support pattern matching or wildcards.

The -match operator stands out from the other matching operators in PowerShell because it allows you to perform advanced pattern matching using regular expressions. With the -match operator, you can match complex patterns, extract data from strings, and perform powerful string manipulations.

Tips and Best Practices for Mastering the PowerShell Match Operator

  1. Understand the basics of regular expressions: Regular expressions can be complex, but having a good understanding of the basics will help you write effective patterns.
  2. Test your patterns: Regular expressions can be tricky, so always test them with different input strings to ensure they match the desired patterns. Using online regex testers like regex101.com or regexr.com can help you build and test your regular expressions. These tools provide real-time feedback and highlight matches in the input string. You can also reference this link for RegEx syntax: Microsoft Regular Expressions Reference Sheet
  3. Break down complex patterns: If you have a complex pattern, break it into smaller parts and test each separately. This makes it easier to debug and understand the pattern.
  4. Remember the performance factor: Regular expressions can be resource-intensive, especially with large input strings. Avoid using overly complex patterns or excessive backtracking to optimize performance.
  5. Document your patterns: Regular expressions can be hard to understand, so document them with comments or explanations to make them more readable and maintainable.
  6. Use match groups to extract specific parts of a matched string.
  7. Use the -like operator for simple searches and the -eq operator for exact matches.

Summary

The PowerShell match operator is a powerful tool for pattern matching in PowerShell. By understanding the basics of regex string patterns and match groups, you can unlock the full potential of this operator. With this article’s tips and best practices, you can start mastering the PowerShell -match operator and take your PowerShell skills to the next level. Whether you’re automating tasks or developing complex scripts, mastering the PowerShell Match Operator will enhance your productivity and enable you to tackle various string manipulation challenges.

The -match operator and regex patterns give PowerShell powerful string manipulation capabilities. Key points:

  • Use anchors like ^ and $ to match position
  • Match multiple patterns with the pipe |
  • Use character classes like \d and \w to match types of characters
  • Apply quantifiers like * and + to match repetition
  • Retrieve matches and groups with the $Matches variable
  • Use match in real-world examples like log parsing and data validation

With regular expressions and the -match operator, you can search, extract, and validate textual data in many ways. It’s a valuable technique for any PowerShell scripter to know. Refer to Replace String in PowerShell: A Comprehensive Guide for replacing text using replace operators in Windows PowerShell.

Now that you have a solid understanding of the PowerShell Match Operator and its capabilities, it’s time to put your knowledge into practice. Experiment with different patterns, test your scripts, and explore the wide range of possibilities that regex string patterns offer in PowerShell. These regular expressions can be used not only with the Match operator but also with Replace, Select-String cmdlet, Split operator, and in the switch statement with the -casesensitive option, etc. (Also in their case-sensitive versions: creplace, csplit).

Remember, practice makes perfect. Happy scripting!

How to use match in PowerShell?

How do I check if one string contains another in PowerShell?

In PowerShell, you can use the -like operator or the Contains() method to check if one string contains another. Here’s an example:
$string = "Hello, World!"
$string -like "World"
$string.Contains("World")

How to match multiple values in PowerShell?

How do you match a word in PowerShell regular expression?

To match a specific word in a PowerShell regular expression, you can use the “\b” anchor to match word boundaries. For example, to match the word “example”, you can use the pattern “\bexample\b”. This will only match the word “example” and not any other words that contain it.

:/>  Как установить wmi?

What is the difference between like and match in PowerShell?

What is $matches in PowerShell?

In PowerShell, $matches is an automatic variable that contains the results of the most recent regular expression match. It is a hashtable that stores the captured groups from the match. This variable is useful when working with regular expressions in PowerShell scripts.

What is the difference between match and Notmatch in PowerShell?

In PowerShell, the “Match” operator finds a match between a string and a regular expression, while the “NotMatch” operator finds a string that does not match a regular expression. The main difference is that “Match” returns true if there is a match, while “NotMatch” returns true if there is no match.


Often you may want to use PowerShell to find all lines in a particular file that do not match a specific pattern.

Note that we used the Regex pattern \d to match numbers between 0 and 9.

Suppose we have a file named employees.txt that contains the ID numbers for various employees at some company.

We can use the Get-Content cmdlet to view the contents of this file:

Массив подстановочных знаков powershell в предложении where

PowerShell regex not match

Notice that this returns all lines in the file that do not contain the pattern that we specified.

Note: You can find the complete documentation for the -notmatch operator in PowerShell here.

PowerShell: How to Use Regex in Switch Statement
PowerShell: How to Use Regex to Capture All Matches
PowerShell: How to Split String Based on Regex Pattern

If statements are conditional logic statements that you can add to your PowerShell scripts. If statements mimic the decision-making process people use every day. If a condition is met, then something happens. For example, if it’s raining outside, I’ll grab an umbrella before heading outside.

If statements in PowerShell function similarly to If statements in other programming languages.

powershell if statements 1

In this diagram, if the condition is true, then it runs a specific command or statement. If the condition is false, it moves onto the next command or statement. Here’s a simple PowerShell example.

Example of PowerShell If statement.

In this example, we created a variable called $eggs and gave it a value of 10. Next, we set a conditional statement that says if $eggs is less than 12, display a message. Since $eggs has a value of 10, the message “You have less than a dozen eggs” is displayed.

Now that we have a basic understanding of If statements, let’s dive a little deeper and go over the syntax and some more advanced examples.

PowerShell If statement syntax

The syntax of If statements in PowerShell is pretty basic and resembles other coding languages.

The condition statement itself can be structured in various different ways. Many condition statements use comparison operators. In my earlier eggcelent example, I used the -lt comparison operation in my conditional statement, which stands for less than. Here is a list of some of the comparison operators you can use in PowerShell.

Keep in mind that condition statements don’t require comparison operators. You can use regular PowerShell cmdlets in the condition statement. For example:

PowerShell example of calling the Test-Path cmdlet to see if a file exists or not.

In this example, we are calling the Test-Path cmdlet to see if a file exists or not. If the file exists, we use the Get-Content and Measure-Object cmdlets to return a word count of the file. If the file does not exist, then the script will just end. As you can see from the screenshot, my MacGyver biography is only 8 words long so far. One of these days, I’ll finish it.

PowerShell If-Else statements

Up to this point, we’ve only talked about If statements. However, you’ll often find If statements accompanied by an Else statement. Else statements allow you to perform an additional action if the condition is not met or returns false.

powershell if statements 4

In this diagram, you can see that we now have two statements that can be executed. One statement if the condition returns true, and one statement if the condition returns false. Here’s a simple PowerShell If-Else statement example.

Example of PowerShell If-Else statement.

In this example, we’ve set the variable $x to a value of 4. We then set our If statement with the condition that if $x is greater than or equal to 3, display the message “$x is greater than or equal to 3.” Lastly, we set our Else statement that if the condition is false, display the message “$x is less than 3.”

You can see from the screenshot that since $x equaled 4, the condition returned true. Now let’s change the value of $x to 1, making the condition return false.

Example of false PowerShell If-Else statement.

Now that the condition returns false, you can see that PowerShell is returning our Else statement, “$x is less than 3.”

Nesting conditional statements

The second and preferred way to nest conditional statements is to use the elseif statement. Here’s an example that builds on the egg example we covered earlier.

Example of nested conditional statements in PowerShell.

In this example, we have three possible outcomes. One if we have exactly 12 eggs. One if we have less than 12 eggs. And one if we have more than 12 eggs. In the screenshot above, we have our $egg variable set to 14, which returned the Else statement, displaying the message “You have more than a dozen eggs.”

Negating PowerShell statements

Sometimes with operators, we need to negate the statement. Using the previous MacGyver example, what if instead of searching for the MacGyver biography, we want to make sure it isn’t there? Here’s an example of how to do that:

Example of how to negate a PowerShell statement.

Now that we know all about If statements, Else statements, and nested conditional statements, let’s bring it all together by creating a script that will give us our dinner plans depending on what day of the week it is.

First, we’ll get the day of the week using the Get-Date cmdlet, returning the DayOfWeek property and assigning it to the $day variable.

$day = (Get-Date).DayOfWeek

Next, we’ll build our nested conditional statement for the different days of the week and assign a different meal for each day.

Example of PowerShell script using If statements, Else statements, and nested conditional statements.

Wrapping up

If you’re interested in other powerful tools, make sure you download a free trial of PDQ Deploy and PDQ Inventory. PDQ Deploy will help you keep your network environment up to date, making deployments and updates a breeze. PDQ Inventory will ensure you have all the information you need to properly manage all of your Windows devices. PDQ Inventory also gives you access to the PowerShell scanner, letting you take advantage of all the cool PowerShell knowledge you just learned in this article.

Brock Bingham candid headshot

Born in the ’80s and raised by his NES, Brock quickly fell in love with everything tech. With over 15 years of IT experience, Brock now enjoys the life of luxury as a renowned tech blogger and receiver of many Dundie Awards. In his free time, Brock enjoys adventuring with his wife, kids, and dogs, while dreaming of retirement.

PowerShell Where-Object cmdlet allows you to filter objects based on their properties. In this PowerShell tutorial, we will focus on the Contains operator within the Where-Object cmdlet and how you can use it. I will also show you PowerShell Where-Object contains examples.

The Contains operator is used with PowerShell Where-Object to find objects in a collection that include a particular property value. It’s important to note that Contains is different from the -like operator, which supports wildcard comparisons, or -match, which uses regular expressions.

A common use case for Contains is when you’re dealing with a collection or an array of values within a single property of an object. Let’s say you want to find all processes that have a certain module loaded. You could do something like this:

Get-Process | Where-Object { $_.Modules -Contains 'ModuleName' }

In this example, Modules is a property that contains a collection of all the modules that each process has loaded. The Contains operator checks to see if ‘ModuleName’ is in that collection.

Here is an example:

Imagine you have a directory of files, and you want to find all files that contain a specific string in their name. You can use a filter with contains in Where-Object.

Get-ChildItem | Where-Object { $_.Name -Contains 'Report' }

This command retrieves all items in the current directory and filters them based on whether their name contains the string ‘Report’.

:/>  Как показать часы с секундами на Windows 10 -

When using Contains in Where-Object in PowerShell, remember that it’s case-sensitive and it looks for an exact match within a collection. If you need a case-insensitive search or partial matching, you might want to consider using -like with wildcards or -match with a regular expression instead.

It’s also worth noting that Contains is not the same as In, which checks if a single value is in a collection. The syntax and use cases are different:

'ServiceName' -In (Get-Service).Name

This checks if ‘ServiceName’ is in the collection of names of all services.

PowerShell where-object contains string

When working with PowerShell, you might need to filter objects based on whether a string property contains a particular substring. This is where the Where-Object cmdlet comes into play, allowing you to sift through a collection of objects and pick out the ones that match certain criteria.

However, there’s a common misconception when it comes to using the term “contains” with Where-Object. In PowerShell, the -contains operator is used to check for the presence of a value within a collection (array), not for substring checking within a string property. To check if a string property of an object contains a particular substring, you would typically use the -like operator with wildcard characters, or the -match operator which uses regular expressions.

Here’s an example of using Where-Object with the -like operator to find a string within another string:

Get-Process | Where-Object { $_.ProcessName -like '*notepad*' }

In this example, we’re filtering the output of Get-Process to only show processes where the ProcessName property contains the substring “notepad”. The asterisks (*) are wildcard characters that match zero or more characters on either side of “notepad”.

You can see the output in the screenshot below:

PowerShell Where-Object Contains

If you need to perform a case-insensitive substring search, -like and -match are inherently case-insensitive in PowerShell. However, you can use the -ccontains-clike, or -cmatch operators for case-sensitive comparisons.

For example, using -match to find a string within another string:

Get-Service | Where-Object { $_.DisplayName -match 'remote' }

This would filter services to those that have “remote” in their DisplayName.

It’s important to note that -match uses regular expressions, which are powerful pattern-matching tools that go beyond simple substring searches. This can be very useful but also requires some understanding of regular expression syntax to use effectively.

In summary, when you want to filter objects in PowerShell based on whether a string property contains a specific substring, you should use -like or -match, not -contains. The -contains operator is intended for use with collections, not strings.

PowerShell where-object not contains

In PowerShell, when you want to filter objects where a property does not contain a specific value, you might think of using a “not contains” operator. However, PowerShell does not have a -notcontains operator for strings. Instead, you need to use the -notlike operator or -notmatch for negating a string match, both of which can be used in conjunction with the Where-Object cmdlet.

Using -notlike

The -notlike operator is used with Where-Object to exclude objects where a string property does not match a specified pattern, which can include wildcards. Here’s an example:

Get-Service | Where-Object { $_.DisplayName -notlike '*SQL*' }

This command will return all services where the DisplayName does not include the substring “SQL”.

Using -notmatch

Alternatively, -notmatch uses regular expressions for pattern matching and can be used to perform more complex negations:

Get-Process | Where-Object { $_.ProcessName -notmatch '^conhost$' }

The above command will return a list of processes where the ProcessName does not exactly match “conhost”. The ^ and $ are regular expression anchors for the start and end of the string, respectively.

Dealing with Collections

If you’re dealing with a property that is a collection (array) and you want to exclude objects where the collection contains a certain value, you use -notcontains. This is the correct use of -notcontains in PowerShell:

$myArray = 'apple', 'banana', 'cherry'
$myArray -notcontains 'orange' # This returns True because 'orange' is not in the array

However, when filtering with Where-Object, you would do something like this:

$myObjects | Where-Object { $_.SomeCollectionProperty -notcontains 'SomeValue' }

In this example, $myObjects is a collection of objects, each with a property SomeCollectionProperty that is itself a collection. The -notcontains operator is used to filter out the objects where SomeCollectionProperty does not contain ‘SomeValue’.

When you want to filter objects based on the absence of a substring within a string property, you should use -notlike or -notmatch with Where-Object in PowerShell. When dealing with a collection property and you want to exclude objects where the collection contains a specific value, you would use -notcontains.

PowerShell where-object does not contain

In PowerShell, when you need to filter objects based on the absence of a certain value within a property that is a collection (like an array), you can use the -notcontains operator with the Where-Object cmdlet in PowerShell. However, if you’re looking to check if a string property does not contain a specific substring, you will need to use the -notlike or -notmatch operators instead, as -notcontains is not designed for string containment checks.

Using -notlike for Strings

The -notlike operator is used in string comparisons where you want to return objects that do not match a specific pattern. This pattern can include wildcards, such as the asterisk (*), which represents any number of characters. Here’s an example:

Get-ChildItem | Where-Object { $_.Name -notlike '*temp*' }

This command will return all items where the Name property does not include the substring “temp”.

Using -notmatch for Strings

The -notmatch operator uses regular expressions for pattern matching and is used to exclude objects where a string property matches a specified regex pattern. Here’s an example:

Get-Process | Where-Object { $_.ProcessName -notmatch 'chrome' }

This command will return all processes where the ProcessName does not contain the substring “chrome”.

Using -notcontains for Collections

When dealing with properties that are collections, the -notcontains operator is appropriate. It checks if a collection does not contain a specific value. For example:

$fruitList = 'apple', 'banana', 'cherry'
$fruitList -notcontains 'grape' # This returns True because 'grape' is not in the list

In the context of Where-Object, you can use -notcontains to filter out objects where a collection-type property does not contain a certain value:

$myObjects | Where-Object { $_.FruitList -notcontains 'grape' }

In this example, $myObjects might be a collection of objects, each with a property FruitList that is a collection of strings representing fruits. The -notcontains operator is used to return only the objects where FruitList does not contain the string “grape”.

When you want to filter out objects in PowerShell where a string property does not contain a certain substring, you should use -notlike or -notmatch. When you need to exclude objects based on the absence of a value within a collection property, use -notcontains.

PowerShell where-object contains examples

Let us check out two examples related to PowerShell where-object contains.

Example 1: Filtering an Array with -contains

Let’s say you have an array of numbers, and you want to find out if the array contains a specific number:

$numbers = 1, 2, 3, 4, 5
$numbers -contains 3

This will return True because the number 3 is in the array $numbers.

Example 2: Filtering Objects with a Property Containing a Certain Value

$myObjects | Where-Object { $_.PropertyArray -contains 'Value' }

In this example, $myObjects might be a collection of objects, and PropertyArray is a property on those objects that is an array. The command filters for objects where PropertyArray contains the string “Value”.

Conclusion

The Where-Object cmdlet with the Contains operator is very useful in PowerShell for filtering objects based on the contents of their properties. Also, we discussed the below topics:

  • PowerShell where-object contains
  • PowerShell where-object contains string
  • PowerShell where-object not contains
  • PowerShell where-object does not contain
  • PowerShell where-object contains examples

You may also like:

I’m struggling with a PowerShell Where clause with an array that contains wildcards. Here’s the command in my much larger code,

$excludedOUs = @("*OU=Loaners,*", "*OU=InStock,*", "*OU=Conference Room,*","*OU=Training,*") 
Get-ADComputer -SearchBase $targetOU -Property LastLogonDate,LastLogon | 
          Where-Object { $_.DistinguishedName -notin $excludedOUs } | Select-Object Name,DistinguishedName, @{l='LastLogonDate';e={[DateTime]::FromFileTime($_.LastLogon)}}
$excludedOUs = @("Loaners", "InStock", "Conference Room", "Training")

I would prefer it. But, I need to use the wildcards because the sub-OU is only a part of the DistinguishedName property. Additionally, the array may not always be limited to just these four items. It might be a single item, or none, or dozens. I won’t know how others in the organization will use this. Any suggestions are appreciated.

Оставьте комментарий