Home > other >  PowerShell - import CSV with # as the first header
PowerShell - import CSV with # as the first header

Time:10-16

I'm having a problem importing this CSV and extracting the specific columns that I need. If I manually remove the first column or change the column heading to anything else and save the CSV, then it works. But If I have "#" as the first column heading it messes up. and the output is not correct and only one random column is shown.

CSV headers

CSV image

Code:

 $Headers = @(
    "Workstation Type"
    "Model"
    "Asset Tag"  
)
Import-Csv 'C:\CSVFiles\DeployedInventory_Workstations.csv' | Select $Headers| Export-Csv -Path 'C:\CSVFiles\DeployedInventory_Workstations2x.csv'-NoTypeInformation

CodePudding user response:

A # as the first column name causes Import-Csv to interpret the header line as a comment line - see GitHub issue #13857.

You can work around this by specifying an alternative header via the -Header parameter:

$inputHeaders = 'HashSign', 'Asset Tag', 'Workstation Type', 'Make', 'Model'
$headers = 'Workstation Type', 'Model', 'Asset Tag'

Import-Csv C:\CSVFiles\DeployedInventory_Workstations.csv -Header $inputHeaders | 
  Select-Object $headers | 
    Export-Csv C:\CSVFiles\DeployedInventory_Workstations2x.csv -NoTypeInformation
  • Related