Powershell从ForEach循环导出为CSV

时间:2015-12-08 15:11:28

标签: csv powershell

我是Powershell的新手,但我已经尽力了。 我试图创建一个脚本来将文件复制到Array中所有XP机器的All Users Desktop。脚本基本上说"如果机器可以ping通,复制文件,如果没有,不要。"然后,我想将此信息导出到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."    

3 个答案:

答案 0 :(得分:2)

问题在于:

SELECT TOP 50 --or however many you like
    DerivedUnionOfTwoTables.[ID],
    DerivedUnionOfTwoTables.[Source]
FROM 
    (
    (SELECT NEWID() AS [Random ID], [ID], 'Table B' AS [Source] FROM B)
    UNION ALL
    (SELECT NEWID() AS [Random ID], [ID], 'Table C' AS [Source] FROM C)
    ) DerivedUnionOfTwoTables
ORDER BY 
    [Random ID] DESC

foreach循环的每次迭代都保存到#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 。覆盖之前的内容,即前一次迭代。这意味着只有最后一次迭代才会保存到$Output并导出。因为您正在运行PowerShell v2,所以我建议将整个foreach循环保存到变量中并导出它。

$Output

答案 1 :(得分:0)

您可能希望附加export-csv以将项添加到csv文件中 这是一个例子

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

答案 2 :(得分:-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 
}