title: Gather info through several foreach and then export-csv at the end of script
body: <p>I have a script that scans all my servers in my domains and outputs to two separate CSV files - one simple and one extensive.</p>
  
  <p>I write one line at the time to my csv.. This results in thousands of file-open and file-close.. I've lurked around and understand that I should first gather all the info and write it all in one sweep at the end of the script. But how do I do this with export-csv (preferably using a function)? </p>
  
  <p>And is there a way I can use the same function for short and long list?</p>
  
  <p>The script performs numerous tasks on each domain/server, but I've trimmed it down to this for your viewing pleasure:</p>
  
  <pre><code>$domains = "no","se","dk"
  
  # Loop through specified forests
  foreach ($domain in $domains) {
  
      # List all servers
      $servers = Get-QADComputer 
  
      # Looping through the servers
      foreach ($server in $servers) {
  
          # GENERATE LONGLIST #
          # Ping server
          if (Test-Connection -ComputerName $server.name -count 1 -Quiet )
          {
              $Reachable = "Yes"
  
              # Fetch IP address
              $ipaddress = [System.Net.Dns]::GetHostAddresses($Server.name)|select-object IPAddressToString -expandproperty IPAddressToString
  
              # Formatting output and export all info to CSV
              New-Object -TypeName PSObject -Property @{
                  SystemName = ($server.name).ToLower()
                  Reachable = $Reachable
                  Domain = $server.domain
                  IPAddress = $IPAddress
                  } | Select-Object SystemName,Domain,IPAddress| Export-Csv -Path "longexport.csv" -append    
          } 
          else # Can't reach server
          {
              $reachable = "No"
              $IPAddress = "Unknown"
  
              # Formatting output and export all info to CSV
              New-Object -TypeName PSObject -Property @{
                  SystemName = ($server.name).ToLower()
                  Reachable = $Reachable
                  Domain = $server.domain
                  } | Select-Object SystemName,Domain,IPAddress| Export-Csv -Path "shortexport.csv" -append
          }
      }
  }
  </code></pre>
  
  <p>(and let me just say that I know that I cannot do -append with export-csv, but I am using a function that let's me do this..)</p>