2017-06-14 89 views
2

我想創建一個腳本,該腳本將訪問.txt文件中的計算機並從每個計算機獲取最新的日誌文件,並將文件和計算機名稱輸出到新文檔中。我四處搜尋,覺得自信可以通過以某種方式結合以下兩個示例來實現這一目標,但我並不完全知道如何。 要在多臺計算機上的相同位置獲得文件:從多臺計算機(powershell)獲取最新日誌文件

$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 
} 
} 

要獲取最新的文件目錄中的

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

回答

1
  • 刪除輸出文件;但你可以覆蓋它。
  • 把一切都放在變量中;但你只用它們一次。
  • 組成你自己的管道分隔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 
相關問題