John Balan
John Balan

Reputation: 43

Adding to a CSV

I have the following code that basically gets the servername and adds it to a CSV on a UNC. The problem I am having is that if I run it multiple times it keeps appending the header and adding the 2nd server.

First run this is how the file looks:

ServerName
Server1

Second run this is what happens:

ServerName
Server1
ServerName
Server2

How can I prevent this so that the server just gets appended instead of the header being written each time?

This is how my code looks:

$servername = $env:computername

# convert string to an object, otherwise if you output to a CSV it will save the
# strings length instead of the servername

# This entry is for testing
#$servername = "test1"

$obj_list = $servername | Select-Object @{Name='ServerName';Expression={$_}}

# converts to an object and sets no header for the column
#$obj_list | ConvertTo-Csv -NoTypeInformation | % {$_.Replace('"','')} | select -Skip 1 | Add-Content \\test\d$\citrixservers\test1.csv 
$obj_list | ConvertTo-Csv -NoTypeInformation | % {$_.Replace('"','')} | Add-Content \\test\d$\citrixservers\servers.csv

Upvotes: 0

Views: 51

Answers (2)

Adam Bertram
Adam Bertram

Reputation: 4198

You need to use Export-CSV with the -Append parameter rather than ConvertTo-Csv. Here's one way to do it.

$servers = @('server1','server2')
foreach ($server in $servers) {
    [pscustomobject]@{'ServerName' = $server} | Export-Csv -Append -Path C:\Servers.csv
}

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200473

Skip the header if the file already exists:

$csv = '\\test\d$\citrixservers\servers.csv'

$skip = if (Test-Path -LiteralPath $csv) { 1 } else { 0 }

$obj_list | ConvertTo-Csv -NoType |
  Select-Object -Skip $skip |
  ForEach-Object { $_.Replace('"','') } |
  Add-Content \\test\d$\citrixservers\test1.csv

Upvotes: 1

Related Questions