2017-02-27 397 views
0

我需要幫助將日誌直接保存到txt文件。我製作了一個簡單的服務器和電腦監控腳本。基本上我只需要知道它是在線還是離線,但是我需要日誌直接保存,無論輸出是什麼。如何在Powershell中保存實時輸出到txt文件?監視腳本

While ($true) { 
    $ServerName = Get-Content "E:\ServerList.txt" 
    foreach ($Server in $ServerName) { 
     if (test-Connection -ComputerName $Server -Count 3 -quiet) { 
      Write-Host "$Server is Online " -ForegroundColor Green ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss") 
     } else { 
      Write-Host "$Server - is Offline " -ForegroundColor Red ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss") 
     } 
    } 

我該如何改進?

+0

那麼是什麼問題?如何寫入日誌文件? – vonPryz

+0

是的,我只是希望輸出可以實時保存到txt文件並且保存日期。基本上任何輸出顯示都會直接保存到文本文件中,如日誌文件。你可以幫助Tnx –

回答

1

可以使用出文件 cmdlet來-append交換機將數據保存在記錄.txt文件。

在這個例子中,你將有兩個,信息輸出到控制檯和文件過多:

$LogFile = 'C:\log.txt' 
While ($true) { 
    $ServerName = Get-Content "E:\ServerList.txt" 
    foreach ($Server in $ServerName) { 
     if (test-Connection -ComputerName $Server -Count 3 -quiet) { 
      Write-Host "$Server is Online " -ForegroundColor Green ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss") 
      "{0}`t{1} is Online " -f (Get-Date).toString("yyyy/MM/dd HH:mm:ss"),$Server | Out-File $LogFile -Append -Force 
     } else { 
      Write-Host "$Server - is Offline " -ForegroundColor Red ;(Get-Date).toString("yyyy/MM/dd HH:mm:ss") 
      "{0}`t{1} is Offline " -f (Get-Date).toString("yyyy/MM/dd HH:mm:ss"),$Server | Out-File $LogFile -Append -Force 
     } 
    } 
} 
+0

驚人的,這就是我要找的。你能不能簡單地向我解釋這一行「{0}'t {1}」,這個新的powershell thingy,我從這裏和從幫助菜單學到的大部分。 xD –

+0

將{0} {1}等放入字符串中作爲您希望變量出現的位置標記,緊接着使用-f運算符跟隨字符串,最後使用逗號分隔的變量列表,這些變量將用於填充地點標記。您可以將我的答案標記爲答案,這樣可以幫助其他類似靜默的人。 :-) –

+0

謝謝基里爾帕什科夫先生。感謝幫助! :-) –

相關問題