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

Multiple conditions in Powershell Where statement

The following CSV file contains a representative data sample of a larger file:

InventoryMaster.csv

ProductID, Location ID, Bin ID
7634,80,233
7635,80,
7636,,416
7637,,
7638,,
7639,80,112

There is a use case to remove lines from the CSV file where neither the Location ID nor the Bin ID are populated. So the 4th and 5th lines in the sample file should be removed. Here is the Powershell script thus far:

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

Write-Host "Remove certain lines in CSV file -"
$file = "C:\Users\knot22\Downloads\InventoryMaster.csv"
(Import-Csv $file) |
Where { $_."Location ID" -ne "" -and $_."Bin ID" -ne "" } |    # remove lines with no values in Location ID and Bin ID fields
Export-Csv $file -NoTypeInformation -UseQuotes AsNeeded

Actual result:

ProductID,Location ID,Bin ID
7634,80,233
7639,80,112
7640,80,119

Expected result:

ProductID, Location ID, Bin ID
7634,80,233
7635,80,
7636,,416
7639,80,112
7640,80,119

The Where statement is not working as expected. How can it be changed to achieve the expected result?

>Solution :

You want to get the rows where a location ID is present OR a bin ID is present – so use the -or operator instead of -and:

Where { $_."Location ID" -or $_."Bin ID" }

Any empty string will be interpreted as "falsy" by PowerShell’s boolean conversion logic, so a row with neither will evaluate as $false -or $false (= $false), whereas any row that has a value in either column is evaluated as $true -or $false (= $true) or $false -or $true (= $true)

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