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

Software & CodingMicrosoft TechnologiesPowerShell

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

raja
Published on 01-Sep-2021 08:07:17
Advertisements