How to create dynamic columns (headers) in CSV using PowerShell?


To create dynamic columns or headers using CSV, we can use multiple methods but the one method that I find most suitable is the PSObject method.

Let assume that your CSV column headers depend on the input provided by the user. Input can be a text file, user prompt for headers, array, etc. For this example, we will use the text file as input.

We have the below columns (headers) to create in the CSV file.

We will use the below command to create headers using PSObject and then export them into the CSV file.

$object = New-Object psobject
foreach($item in (gc C:\Temp\DynamicHeaders.txt)){

   $object | Add-Member -MemberType NoteProperty $item -Value ''
}

$object | Export-Csv C:\Temp\Customheaders.csv -NoTypeInformation

Once you check the CSV file, it will be created as what we provided in the text file.

Output

Updated on: 01-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements