简体   繁体   中英

How to handle dynamic columns for CSV file using Import-csv in PowerShell

CSV file does not have headers, Column may differ each time. I want to compare with first column of csv file, but while exporting I would display the full row.

$getErrorCodes= {102,103}

CSV FILE( No headers)
101,101,101
102,102,102

Here is my code

Import-Csv $CSVFile -Header col1 | Where-Object {!($getErrorCodes.Contains($_.col1)) } | Export-Csv "resultfile.csv"

Current output
101

Expected output
101,101,101

For dynamic header, I used like this. Dynamically will change $headers variable accordingly column count on csv.

$headers = 'Col1,Col2,Col3'

$headercolumns = $headers.ToString().Split(",") 
  
Import-Csv $CSVFile -Header  $headercolumns | Where-Object {!($getErrorCodes.Contains($_.col1)) } | Export-Csv  "resultfile.csv"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM