In PowerShell, you can use the Where-Object cmdlet with the -contains operator to filter a collection based on whether a property contains a certain value.
The following method shows how you can do it with syntax.
Method 1: Filter elements containing the string using Where-Object
$languages = @("Python", "C#", "C", "C++", "VB", "Java", "Go")
$result = $languages | Where-Object {$_ -contains "C++"}
$result
This example will filter out elements that contain the string “C++” and display the result on the terminal.
The following example shows how you can use this method.
Use Where-Object to Filter Elements Containing String
The following PowerShell script shows how you can do it.
# Define the list of languages $languages = @("Python", "C#", "C", "C++", "VB", "Java", "Go") # Use where-object to filter elements containing "C++" $result = $languages | Where-Object {$_ -contains "C++"} # Output the result $result
Output:
In this example, we have defined a collection $languages
that contains the list of programming languages.
We then pipe the $languages
to the Where-Object cmdlet to filter out elements that contain the string “C++” using the -contains operator, and the result is stored in the $result
variable.
Finally, the filtered result is printed.
Conclusion
I hope the above article on using the Where-Object cmdlet with -contains operator to filter a list based on the condition specified is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.