2

I am new to powershell scripting and I am looking for a way to add 2 new rows at the top of the already present csv file. Things that I have tried is replacing the header and rows with the new rows. I am looking for a way to add 2 new rows above the header in CSV.

5
  • 1
    Welcome to stack overflow. Can you please have a look at this link: stackoverflow.com/help/how-to-ask We need to see your code. Also when you say Things that I have tried we would need to know what you tried. Thanks. Commented Oct 5, 2019 at 15:28
  • Maybe this answer will help: stackoverflow.com/a/53470146/3099345 Commented Oct 5, 2019 at 16:09
  • the easiest method is to [1] create an array of new objects that represent the new rows, [2] import the CSV file via Import-CSV, [3] add the 2nd to the 1st, [4] export the CSV file via Export-CSV. Commented Oct 5, 2019 at 17:46
  • 1
    Does the CSV file have headers? Where do the 2 new rows come from? (another CSV or strings formatted to fit the CSV or..?) Commented Oct 5, 2019 at 19:02
  • 1
    By the way, I am looking for a way to add 2 new rows above the header in CSV wil mean you are creating an invalid CSV file. Headers (if any) need to come first. Commented Oct 5, 2019 at 19:39

1 Answer 1

1

You mention that you want to add the new lines above the header, which means that no CSV-specific processing is needed - it sounds like you're asking how to prepend lines to an existing text file (which happens to contain CSV - note that the resulting file will no longer be a valid CSV file).

E.g., assuming a target file named some.csv:

Note: Best to make a backup of the target file before trying these commands.


If the input file is small enough to fit into memory as a whole:

Reading the entire target file into memory as a single string with Get-Content -Raw allows for a convenient and concise solution:

Set-Content -LiteralPath some.csv -NoNewLine -Value (
  @'
New line 1 above header
New line 2 above header

'@ + (Get-Content -Raw some.csv)
)

Note that Set-Content applies a default character encoding (the active ANSI code page in Windows PowerShell, UTF-8 without BOM in PowerShell Core), irrespective of the current encoding of some.csv, so you may have to use the -Encoding parameter to specify the encoding explicitly.

Also note that the single-quoted here-string (@'<newline>...<newline>'@) uses the same newline style (CRLF (Windows-style) vs. LF (Unix-style)) as the enclosing script, which may not match the style used in some.csv - though PowerShell itself has no problem processing files with mixed newlines styles.


If the file is too large to fit into memory, use a streaming (line-by-line) approach:

$ErrorActionPreference = 'Stop'

# Create a temporary file and fill it with the 2 new lines.
$tempFile = [IO.Path]::GetTempFileName()
'New line 1 above header', 'New line 2 above header' | Set-Content $tempFile

# Then append the CSV file's lines one by one.
Get-Content some.csv | Add-Content $tempFile

# If that succeeded, replace the original file.
Move-Item -Force $tempFile some.csv

Note: Use of the Get-Content, Set-Content and Add-Content cmdlets is convenient, but slow; the next section shows a faster alternative.


If performance matters, use .NET types such as [IO.File] instead:

$ErrorActionPreference = 'Stop'

# Create a temporary file...
$tempFile = [IO.Path]::GetTempFileName()

# ... and fill it with the 2 new lines.
$streamWriter = [IO.File]::CreateText($tempFile)
foreach ($lineToPrepend in 'New line 1 above header', 'New line 2 above header') {
  $streamWriter.WriteLine($lineToPrepend)
}

# Then append the CSV file's lines one by one.
foreach ($csvLine in [IO.File]::ReadLines((Convert-Path some.csv))) {
  $streamWriter.WriteLine($csvLine)
}

$streamWriter.Dispose()

# If that succeeded, replace the original file.
Move-Item -Force $tempFile some.csv
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.