powershellcsvfilterpropertiesselect-object

Powershell Select-Object Property multiple comparisons same property


I am using Select-Object to filter a CSV to get the necessary columns. When I use this: $Filter = $Csv | Select-Object ($Csv[0].PSObject.Properties.Name -like "*Results*" it filters all columns and displays everything containing results, this works fine. But how do I get it to keep my first column where the header is "Sample" as well as keeping the results? I have tried without success:

$Filter = $Csv | Select-Object ($Csv[0].PSObject.Properties.Name -like "*Results*" -and $Csv[0].PSObject.Properties.Name -like "Sample")

I understand you can add multiple properties comma separated but I am looking for the same property but with multiple matching parameters.

The output would include a column that have header name "Sample" and columns that would contain the word "Results". They both work individually in the first line of code provided, but how do i make it work together with both matching strings?

Edit: Expected output added


Solution

  • In order to pass multiple property (column) names to the (possibly positionally implied) -Property parameter of the Select-Object cmdlet using an expression ((...)), you must pass a flat array.

    To that end, use + for concatenation, making sure that (at least) the LHS is an array.

    The following places the Sample property first, using @(...), the array-subexpression operator to wrap it in an array:

    $Csv |
      Select-Object (@('Sample') + ($Csv[0].PSObject.Properties.Name -like "*Results*"))