2015-12-08 68 views
1

我是Powershell的新手,但我已經盡力了。 我試圖創建一個腳本來將文件複製到陣列中所有XP機器的所有用戶桌面。該腳本基本上說:「如果機器是可pingable的,則複製該文件,如果沒有,則不要。」然後我想將這些信息導出爲CSV文件以供進一步分析。Powershell從ForEach Loop導出爲CSV

我已經設置了所有,但不管我做什麼,它只會導出它運行的最後一臺PC。它似乎貫穿所有PC(經過輸出到txt文件的測試),但它不會將所有機器記錄到CSV。任何人都可以提供任何建議嗎?

$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."  

回答

0

問題是這樣的:

#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 

您的foreach循環的每次迭代保存到$Output。覆蓋之前的內容,即先前的迭代。這意味着只有最後一次迭代纔會保存到$Output並導出。由於您運行的是PowerShell v2,因此我建議將整個foreach循環保存到一個變量中並導出。

$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 
+0

我試過把$輸出| Export-CSV C:\ GPoutput.csv放入數組中,但它再次覆蓋自身,因爲不允許使用-append。 我也嘗試將整個foreach循環保存到一個變量中,但這帶來了錯誤:「in expression or statement」中的「意外標記」。 – Groveham

+0

您必須使用v2。我建議然後將整個foreach循環存儲到$ Output和export中。 –

-1

你在這裏。這使用PSCustomObject,它比New-Object更快地枚舉數據。在每個循環之後還會附加.csv文件,因此不會覆蓋以前的數據。

foreach ($Computer in $ArrComputers) { 

$Reachable = Test-Connection -Cn $Computer -BufferSize 16 -Count 1 -ea 0 -quiet 

#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 
     [PSCustomObject]@{ 
     SystemName = $Computer 
     Reachable = $reachable 
     Result = $details 
     } | Export-Csv C:\yourcsv.csv -notype -Append 
} 
+0

這是行不通的,因爲他正在使用v2。 PSCustomObject和'-Append'是v3 +。 –

+0

錯過了他提到XP機器的地方。 – bentek

0

你會想追加出口CSV將項目添加到CSV文件 下面是一個例子

foreach ($item in $ITGlueTest.data) 
{ 
$item.attributes | export-csv C:\organization.csv -Append 
}