Exporting an array to csv

Welcome Forums General PowerShell Q&A Exporting an array to csv

  • This topic has 1 reply, 2 voices, and was last updated 1 month ago by
    Participant
    .
Viewing 1 reply thread
  • Author
    Posts
    • #233068
      Participant
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      I have created the script below and the values are being added into the CSV, but they are being duplicated on each line/column, example below.

      RTC_Status                RTME_Version             UserName
      Connected,Connected 2.6.0.2030,2.6.0.2030 domain\user1,domain\user2
      Connected,Connected 2.6.0.2030,2.6.0.2030 domain\user1,domain\user2

      $Array = @() ## Create Array to hold the Data 
      $Computers = Get-Content -Path C:\Users\username\Downloads\Computernames.txt 
      
      foreach ($Computer in $Computers) 
      { 
      $Result = "" | Select RTC_Status,RTME_Version,UserName 
      $OS = Get-WMIObject -ComputerName $Computers -Namespace ROOT\Citrix\hdx\RTOptPack -Class Citrix_HDXRTConnector 
      $username = Get-WmiObject -ComputerName $Computers –Class Win32_ComputerSystem 
      $Result.RTC_Status = $OS.RTC_Status -join ',' 
      $Result.RTME_Version = $OS.RTME_Version -join ',' 
      $Result.UserName = $username.UserName -join ',' 
      $Array += $Result ## Add the data to the array } 
      $Array | Export-Csv C:\Users\username\Downloads\file.csv -NoTypeInformation
      • This topic was modified 1 month ago by blue_ken28.
      • This topic was modified 1 month ago by blue_ken28.
    • #233092
      Participant
      Topics: 5
      Replies: 2372
      Points: 6,005
      Helping Hand
      Rank: Community MVP

      There’s a cleaner (and easier) way to build such a report …

      $ComputerList = Get-Content -Path C:\Users\username\Downloads\Computernames.txt 
      
      $Results = foreach ($Computer in $ComputerList) { 
          $OS = Get-WMIObject -ComputerName $Computer -Namespace ROOT\Citrix\hdx\RTOptPack -Class Citrix_HDXRTConnector 
          $username = Get-WmiObject -ComputerName $Computer –Class Win32_ComputerSystem 
      
          [PSCustomObject]@{
              RTC_Status = $OS.RTC_Status -join ','
              RTME_Version = $OS.RTME_Version -join ',' 
              UserName   = $username.UserName -join ',' 
          }
      }
      
      $Results | 
          Export-Csv C:\Users\username\Downloads\file.csv -NoTypeInformation

      You use a loop to iterate over each single element of a list but you did not reference single elements inside your loop. You referenced the entire list instead. 😉

Viewing 1 reply thread
  • You must be logged in to reply to this topic.