Reputation: 11
I'm trying to do something fairly simple - I have a string array with multiple elements. I want to create another string array with the elements that don't contain a certain substring.
Unfortunately using both -notlike
and -notcontains
, my $l
returns no entries. I expect it to return one entry with "two" in it. I suspect I'm doing something simple wrong, but I haven't been able to figure it out.
$s = "one","two"
Write-Host "s:"
Write-Host "$s"
I have tried both -notlike and -notcontains and both return $l as empty. I am NOT using both at the same time.
#$l = Where-Object ($s -notlike "on")
$l = Where-Object ($s -notcontains "on")
Write-Host "l:"
Write-Host "$l"
Again, I am wanting $l to return with one element "two" since "on" is matched in "one".
Upvotes: 1
Views: 444
Reputation: 68243
@Mark Wragg's comments and answer are spot on with regard to the wildcard syntax required for the -notlike
operator.
Beyond that, the Where-Object
clause isn't necessary at all, since the comparison operators will also operate as filters when used against an array:
$s = "one","two"
"s: $s"
$l = $s -notlike "on*"
"l: $l"
Upvotes: 3
Reputation: 23355
-NotLike
will work, but you need to use curly braces around your expression in the Where-Object
(you are currently using brackets) and you need to use a *
as a wildcard character.
In the Where-Object
you also need to use $_
as your variable. This is a special automatic variable that represents the current item in the pipeline as it is being processed (for example, "one", then "two"):
$s = "one","two"
"s: $s"
$l = $s | Where-Object { $_ -notlike "on*"}
"l: $l"
Upvotes: 4