Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter a CSV file with multiple conditions using PowerShell

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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*' }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading