2017-06-14 4 views
2

.txtファイル上のコンピュータにアクセスし、それぞれから最新のログファイルを取得し、ファイルとコンピュータ名を新しいドキュメントに出力するスクリプトを作成します。私は次の2つの例を何らかの形で組み合わせることでこれを達成できると自信を持って検索しましたが、私は完全にはわかりません。複数のコンピュータ上の同じ場所からファイルを取得するには :出力ファイルを消去したディレクトリにある最新のファイル複数のコンピュータから最新のログファイルを取得する(powershell)

$dir = "C:\test_code" 
$latest = Get-ChildItem -Path $dir | Sort-Object LastAccessTime -Descending 
| Select-Object -First 1 
$latest.name 

答えて

1
  • を取得するには

    $Computers = get-content "C:\Computers.txt" 
    $OutFile = "C:\Results.txt" 
    
    #Erase an existing output file so as not to duplicate data 
    out-file -filepath $OutFile 
    
    foreach ($Computer in $Computers) 
    { 
    
    if (test-path \\$computer\c$\temp\logfile.txt) #test to make sure the file 
    exists 
    { 
    #Get the CreationTime value from the file 
    $FileDate = (Get-ChildItem \\$computer\c$\temp\logfile.txt).CreationTime 
    
    #Write the computer name and File date separated by a unique character you 
    can open in Excel easy with" 
    "$Computer | $FileDate" | out-file -FilePath $OutFile -Append -Encoding 
    ascii 
    } 
    else 
    { 
    #File did not exist, write that to the log also 
    "$Computer | FILE NOT FOUND" | out-file -FilePath $OutFile -Append -Encoding 
    ascii 
    } 
    } 
    

    。ただ上書きすることができます。

  • すべてを変数に入れます。しかし、それらは一度だけ使用します。
  • 二重出力処理とエンコード奇妙な独自のパイプで区切られたCSVを構成するPSはかなり良いCSV処理を持っています。
  • ファイルが存在するかどうかをテストする必要はありません。ファイルが何であるかわからないからです。

Get-Content -Path "C:\Computers.txt" | ForEach-Object { # Each computer 

    # Get latest file 
    $Latest = Get-ChildItem -Path "\\$_\c$\temp\*" | 
        Sort-Object -Property LastAccessTime -Descending | 
        Select-Object -First 1 

    # Make a custom object with the three things to go in the output CSV 
    [PsCustomObject]@{ 
     Computer  = $_ 
     FileName  = if ($latest) { $Latest.Name }   else { "File not found" } 
     CreationTime = if ($latest) { $Latest.CreationTime } else { "n/a" } 
    } 

} | Export-Csv c:\results.csv -NoTypeInformation -Encoding ASCII # write the output csv 
関連する問題