Export Object to CSV

This topic contains 3 replies, has 3 voices, and was last updated by  js 3 months ago.

  • Author
    Posts
  • #75275

    Mitzoid1
    Participant

    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

    John Steele
    Participant

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

    • #75281

      Mitzoid1
      Participant

      thanks! 🙂 that worked great. so simple

  • #75481

    js
    Participant

    Or put the export last outside the loop:

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

You must be logged in to reply to this topic.