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