Powershell 从 ForEach 循环导出到 CSV

Gro*_*ham 8 csv powershell export-csv

我是 Powershell 的新手,但我已经尽力了。我正在尝试创建一个脚本来将文件复制到阵列中所有 XP 计算机的所有用户桌面。该脚本基本上是说“如果机器可 ping 通,则复制文件,如果不是,则不复制。” 然后我想将此信息导出到 CSV 文件中以供进一步分析。

我已经设置了一切,但无论我做什么,它都只会导出它运行的最后一台电脑。它似乎运行在所有 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."   
Run Code Online (Sandbox Code Playgroud)

Ben*_*ard 10

问题是这样的:

#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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)