4

私はPowershellを初めて使用しますが、最善を尽くしました。アレイ内のすべての XP マシンのすべてのユーザーのデスクトップにファイルをコピーするスクリプトを作成しようとしています。スクリプトは基本的に、「マシンが 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."   
4

3 に答える 3

6

問題はこれです:

#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
于 2015-12-08T15:19:36.300 に答える
-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 
}  
于 2015-12-08T15:41:22.290 に答える