Home > Net >  How can I create a CSV file and append content to it, in powershell?
How can I create a CSV file and append content to it, in powershell?

Time:10-12

I need to save some information about servers into a csv file. The information that will be saved to this file will be added like a cycle, so, in a way, I need to append information to the file.

I have tried two ways of doing this, but none of them seem to work (the variables ip, id, name and stauts, will not be static in the final version of the script):

  1. with Add-Content

    for($i=0; $i -lt 5; $i  ){
     $OutFile = "C:\information.csv"
    
     $test = Test-Path -Path $Outfile
    
     $id=$i
     $ip="1234$i"
     $name="Server$i"
     $status="up"
    
     if(!$test)
    {
    
        Add-Content -Path $Outfile -Value '"ID","IP","Name","Status"'
    
    }
    

    Add-Content -Path $OutFile -Value $id,$ip,$name,$status

    }

When I run this script, all of the information is put in the same column/header.

enter image description here

  1. Creating empty CSV file and add content to it:

    for($i=0; $i -lt 5; $i  ){
    $OutFile = "C:\information.csv"
    
    $test = Test-Path -Path $Outfile
    
    $id=$i
    $ip="1234$i"
    $name="Server$i"
    $status="up"
    
    if(!$test)
     {
        $newcsv = {} | Select "ID", "NAME","IP","STATUS" | Export-Csv $OutFile
     }
    
    
    $csvfile = Import-Csv $OutFile
    
    $csvfile.ID = $id
    $csvfile.NAME = $ip    
    $csvfile.IP = $name
    $csvfile.STATUS = $status
    
    
    $csvfile | Export-CSV $outfile –Append
    
    
    }
    

When I run this script I get error messages for each header saying:

The property 'ID' cannot be found on this object. Verify that the property exists and can be set.

However, the file is created and the information is put in the correct header, but the content of each header is wrong, and the ID header has a different value from the variable that I created

enter image description here

I way bests suits to append values to a csv file, and what I' doing wrong to have the outputs shown in the pictures?

I'm available to respond to any question regarding this problem. Thank you for your time.

CodePudding user response:

For outputting a valid CSV, collect objects and use Export-Csv.

Try something like this:

$OutFile = "C:\information.csv"

# output 5 dummy servers
0..4 | ForEach-Object {
    [PsCustomObject]@{
        Id     = $_
        IP     = "192.168.1.$_"
        Name   = "Server$_"
        Status = 'Up'
    }
} | Export-Csv -Path $Outfile -NoTypeInformation 

Output when shown on screen:

Id IP          Name    Status
-- --          ----    ------
 0 192.168.1.0 Server0 Up    
 1 192.168.1.1 Server1 Up    
 2 192.168.1.2 Server2 Up    
 3 192.168.1.3 Server3 Up    
 4 192.168.1.4 Server4 Up
  • Related