Powershell – Repeat the csv header twice without “Append” (PowerShell 1.0)

csvpowershell

I have prepared a PowerShell script to export a list of system users in CSV format. The script can output the users list with Export-csv with single header row (the header row at top).

However my requirement is to repeat the header row twice in my file. It is easy to achieve in PowerShell 3.0 with "Append" (e.g. $header | out-file $filepath -Append) Our server envirnoment is running PowerShell 1.0. Hence I cannot do it. Is there any workaround? I cannot manually add it myself.

Thank you.

Best Answer

What you can do is:

  1. Write the CSV with Export-Csv
  2. Read the contents back into a variable with Get-Content
  3. Append/prepend the header line
  4. Write it all back to the file

Like this:

# Path to your file
$File = "C:\My\File.csv"
# Write the CSV file
$Data | Export-Csv $File
# Read it back as plain text
$CSV  = Get-Content $File
# Add the header line at the start
$CSV  = $Header + $CSV
# Write it all back to the CSV file
$CSV  | Set-Content $File