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