Powershell Export to CSV from ForEach Loop

Groveham picture Groveham · Dec 8, 2015 · Viewed 83.4k times · Source

I'm new to Powershell but I've given it my best go. I'm trying to create a script to copy a file to the All Users Desktop of all the XP machines in an Array. The script basically says "If the machine is pingable, copy the file, if not, don't." I then want to export this information into a CSV file for further analysis.

I've set it all but no matter what I do, it will only export the last PC that it ran though. It seems to run through all the PC's (tested with outputting to a txt file) but it will not log all the machines to a CSV. Can anyone give any advise?

$ArrComputers = "PC1", "PC2", "PC3"

foreach ($Computer in $ArrComputers) {
    $Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet
    $Output = @()

    #Is the machine reachable?
    if($Reachable)
    {
        #If Yes, copy file
        Copy-Item -Path "\\servername\filelocation" -Destination "\\$Computer\c$\Documents and Settings\All Users\Desktop\filename" 
        $details = "Copied"  
    } 
    else
    {
        #If not, don't copy the file
        $details = "Not Copied"
    }   

    #Store the information from this run into the array  
    $Output =New-Object -TypeName PSObject -Property @{
        SystemName = $Computer
        Reachable = $reachable 
        Result = $details
    } | Select-Object SystemName,Reachable,Result
}

#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv

Write-output "Script has finished. Please check output files."   

Answer

Benjamin Hubbard picture Benjamin Hubbard · Dec 8, 2015

The problem is this:

#Store the information from this run into the array  
  $Output =New-Object -TypeName PSObject -Property @{
    SystemName = $Computer
    Reachable = $reachable 
    Result = $details
  } | Select-Object SystemName,Reachable,Result
}  
#Output the array to the CSV File
$Output | Export-Csv C:\GPoutput.csv

Each iteration of your foreach loop saves to $Output. Overwriting what was there previously, i.e., the previous iteration. Which means that only the very last iteration is saved to $Output and exported. Because you are running PowerShell v2, I would recommend saving the entire foreach loop into a variable and exporting that.

$Output = foreach ($Computer in $ArrComputers) {
  New-Object -TypeName PSObject -Property @{
    SystemName = $Computer
    Reachable = $reachable 
    Result = $details
  } | Select-Object SystemName,Reachable,Result
}
$Output | Export-Csv C:\GPoutput.csv