Working with CSV files in PowerShell is a common practice. You import the file, loop on its records and you’re good to go. Sometimes however you may find yourself in a situation where you get a file that has blank lines in it, and those lines can break your script. Consider the following CSV content: ## sample.csv ## column1,column2,column3 Value1,Value2,Value3 Value1,Value2,
You might be attempted to do that with:
1
2
| Import-Csv sample.csv |Where-Object {$_.column1 -ne '' -and $_.column1 -ne '' -and $_.column1 -ne ''} |
But what if each record has 20 properties, or even more? This is where the PSObject property comes to rescue. In a nutshell, PSObject allows us to work with any object in the same way without really knowing its structure. PowerShell wraps the base object in a PSObject and provide us a simplified and consistent view of the object, its methods, properties, and so on. One of the properties of PSObject is Properties, and it gives us a list of properties of the base object.
For our purpose, we can process the properties list and filter out those who have a Value of null.
Import-Csv sample.csv |Where-Object { ($_.PSObject.Properties | ForEach-Object {$_.Value}) -ne $null} |Format-List
No comments:
Post a Comment