1

When I do ($env:path).split(";"), there are many elements containing the string bin. I want to have a list of them. I try:

($env:path).split(";") | Where-Object {$_ -contains "bin" } 

But there is no result. If I change the operator to -notcontains, it lists all paths, regardless of containing the string or not. How to make this works?

9

1 Answer 1

3

You are using the wrong comparison operator.

-contains checks if a Collection(array\list\etc) contains one specific element.

@('Z', 'A', 'Q', 'M') -contains 'A' returns $true

But you are working with the single strings of the array: you therefore need to use either -like(for simple wildcard matching) or -match(for regular expression matching)

so ($env:path).split(';') | Where-Object { $_ -match 'bin' }

Also, in more powershell-y way $env:path -split ';' | Where-Object { $_ -match 'bin' }

EDIT: and this is to go even further beyond! $env:path -split ';' -Match 'bin' (thanks @iRon)

(note I made the matching as simple as possible as example, you'll need to test if it works correctly for your needs)

More about Comparison Operators

Sign up to request clarification or add additional context in comments.

6 Comments

it seems that the mindset of PowerShell is to use operators rather than methods, right?
@Ooker yeah, pretty much. The general idea is using the pipeline as much as possible(exceptions apply).
can you recommend any article that explains this in details?
@Daniel that article doesn't seem to address the idea that operators have more advantages than methods in PS
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.