Export Object to CSV

Welcome Forums General PowerShell Q&A Export Object to CSV

This topic contains 3 replies, has 3 voices, and was last updated by

js
 
Participant
1 year, 3 months ago.

  • Author
    Posts
  • #75275

    Participant
    Points: 0
    Rank: Member

    When I run the following code with write-output $obj at the end It prints all of the computers on the screen but when I try to export to csv I only get (one computer) the last computer information in the csv file.

    $Computers = get-content C:\POSH\test.txt
    foreach ($comp in $Computers) {
      $CS = Get-WmiObject -Class Win32_computersystem -ComputerName $comp
      $Encl = Get-WmiObject -Class Win32_Systemenclosure -ComputerName $comp
    
      $props = @{CompName=$cs.name
                 Manufacturer=$cs.manufacturer
                 Model=$cs.model
                 Serial=$encl.serialnumber}
    
        $obj = New-Object -TypeName PSObject -property $props
        Write-Output $obj
     #  $obj | export-csv c:\posh\test.csv -Notype (I only get one computer when I replace write-output with this)
    }
    
  • #75278

    Participant
    Points: 0
    Rank: Member

    You need to use the -append switch. That will add the output to the end of the file.

    • #75281

      Participant
      Points: 0
      Rank: Member

      thanks! 🙂 that worked great. so simple

  • #75481
    js

    Participant
    Points: 207
    Helping Hand
    Rank: Participant

    Or put the export last outside the loop:

    } | export-csv c:\posh\test.csv -Notype 

The topic ‘Export Object to CSV’ is closed to new replies.