0

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.

  • I don't have any machines with PoSH 1.0 to test on, but have you tried Set-Content? – Mathias R. Jessen Aug 25 '14 at 18:34
  • According to technet.microsoft.com/en-us/library/ee176959.aspx , Set-Content will replace entire txt. With Add-Content, it will append the new line at the back. However I want to insert a header at the top of output CSV. – Mark Aug 26 '14 at 1:56
  • Why don't you just call Add-Content and write the header out before you run Export-Csv? – Mathias R. Jessen Aug 26 '14 at 2:50
  • Since Export-Csv do not support -Append, it will overwrite the text wrote by Add-Content. – Mark Aug 26 '14 at 2:58
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.