Here is a small sample of data in a CSV file that needs to be filtered to remove all lines that contain Branch 102 or Name equals Admin.
DataSource.csv
branch,ID,name
102,11056,Jones
103,11057,Henry
102,22000,Admin
103,22001,Admin
102,22002,White
103,22003,George
Here is the first version my PowerShell script, demo.ps1, that works –
$path = "C:\users\knot22\PowerShell"
Import-CSV "$($path)\DataSource.csv" | Where Branch -NotLike '*102*' | Where Name -NotLike '*Admin*' |
Export-CSV "$($path)\DataTarget.csv" -NoTypeInformation -UseQuotes Never
The resulting output of DataTarget.csv is –
branch,ID,name
103,11057,Henry
103,22003,George
However, I’d like to modify demo.ps1 so that the conditions are in a single Where block. I’ve tried this
$path = "C:\users\knot22\PowerShell"
Import-CSV "$($path)\DataSource.csv" | Where Branch -NotLike '*102*' -or Name -NotLike '*Admin*' |
Export-CSV "$($path)\DataTarget.csv" -NoTypeInformation -UseQuotes Never
but it results in an error
"Cannot bind parameter because parameter ‘NotLike’ is specified more
than once. To provide multiple values to parameters that can accept
multiple values, use the array syntax. For example, "-parameter
value1,value2,value3".
This error message implies that the multiple conditions are intended for one parameter. In the use case above, the multiple conditions apply to different parameters.
Is there a way to modify the syntax in the second version of demo.ps1 that attempts to combine the conditions with -and so that it runs successfully? I’m looking to keep the syntax concise.
Also, I’m using PowerShell 7.
>Solution :
The Where-Object cmdlet (alias Where) has two distinct modes of filtering – one for simple property comparison (which is what you’re currently using), and one for more complex filtering scenarios.
For the latter, you’ll need to supply a scriptblock that is then used as a predicate against each input item:
Where { $_.Branch -notlike '*102*' -or $_.Name -notlike '*Admin*' }
Beware that this isn’t the equivalent of your current pipeline – for that, you’ll want to use the -and operator:
Where { $_.Branch -notlike '*102*' -and $_.Name -notlike '*Admin*' }