2012-03-05 146 views
2

所以,假設您想從LAN上的所有桌面上查看類型應用程序的事件日誌中的最後3件事。我的問題是,下面的$ a創建一個數組(我認爲),並且我想把它寫到一個文件中。現在它「工作」,但只是每臺機器吐出幾行空白行。如果$味精=被註釋掉了,我得到這個「異常調用‘加入’與‘2’參數(S):‘值不能爲空’將事件日誌寫入文件,powershell

$servers = "machine1, "machine2" 
$date = (get-date).ToString('yyyyMMdd') 
$file = New-Item -type file "c:\temp\$date-test1.txt" -Force 
$msg = "" 
foreach($server in $servers){ 
    Write-Host "Connect to $server..." 
    add-content $file "$server $date" 
    $a = Get-EventLog -Logname application -ComputerName $server -EntryType warning -newest 3 | 
    Format-Table -Wrap -Property Source,Message -Autosize 
    foreach($element in $a) 
    {[string]::join($element, $msg)} 
    Write-Host $msg 
    #add-content $file $msg 
} 

回答

3

你正在考慮的文本,在沒有對象。管道。不要試圖解析,用繩子周圍加入或混亂。

$servers = "machine1, "machine2" 
$date = (get-date).ToString('yyyyMMdd') 
$file = New-Item -type file "c:\temp\$date-test1.txt" -Force 
Get-EventLog -log Application -Computer $servers -entry Warning -newest 3 | Select MachineName,Source,Message | out-file $file 
+0

首先感謝您的回答是99%完美的答覆。加入這個「物業資源,信息-AutoSize」允許滿事件消息,上面只給你約2/3的第一句話。我添加/更改爲:Get-EventLog日誌應用程序 - 計算機$服務器 - 入口警告-newest 3 | 選擇計算機名稱,來源,消息| 格式 - 表 - 包裝 - 屬性MachineName,源,消息-Autosize | out-file $文件 – user1249998 2012-03-05 21:05:40

+0

您現在就明白了。也就是說,我更簡單的方法的一個缺點是,它假定了一小組計算機,並且它們都在線。更健壯的方法需要錯誤處理,也許嘗試/捕捉或甚至寫入。在這些情況下,ForEach構造可能會更有意義,但我仍然會放棄使用字符串並將輸出管道輸出到Out-File。 – 2012-03-05 21:27:33