2016-03-08 74 views
0

我想用Start-Job同時使用Get-Content file -Wait -Last 1-Last 1來避免打開整個日誌)監視(尾)多個日誌文件。作業意外退出

運行gc $file -Last 1 -Wait允許僅拖尾一個文件。 在Start-Job -Scriptblock中將其包起來立即退出工作。

我有這樣的想法。

Start-Job -Name srv1 -ScriptBlock {Get-Content "\\srv1\$log" -Wait -Last 1} | Select-String "matching some text only" | Out-File D:\autogrep.log} 
Start-Job -Name srv2 -ScriptBlock {Get-Content "\\srv2\$log" -Wait -Last 1} | Select-String "matching some text only" | Out-File D:\autogrep.log} 
Start-Job -Name srv3 -ScriptBlock {Get-Content "\\srv3\$log" -Wait -Last 1} | Select-String "matching some text only" | Out-File D:\autogrep.log} 
Start-Job -Name srv4 -ScriptBlock {Get-Content "\\srv4\$log" -Wait -Last 1} | Select-String "matching some text only" | Out-File D:\autogrep.log} 
Start-Job -Name srv5 -ScriptBlock {Get-Content "\\srv5\$log" -Wait -Last 1} | Select-String "matching some text only" | Out-File D:\autogrep.log} 

任何建議如何解決這個問題?

回答

0

同時向不同作業寫入相同的輸出文件將會創建競爭條件,除非您有一個調度程序來協調寫入訪問。另外,如果您想從UNC路徑讀取日誌,則需要提供路徑爲\\server\share\file

嘗試是這樣的:

$servers = 'srv1', 'srv2', 'srv3', 'srv4', 'srv5' 
$jobs = @() 

$servers | ForEach-Object { 
    $jobs += Start-Job -Name $_ -ScriptBlock { 
    Param($server, $log) 
    Get-Content "\\$server\share\$log" -Wait -Last 1 
    } -ArgumentList $_, 'your.log' 
} 

while ($jobs.State -contains 'Running') { 
    $jobs | Where-Object { $_.hasMoreData } | 
    Receive-Job | 
    Select-String 'matching some text only' | 
    Out-File 'D:\autogrep.log' -Append 
    Start-Sleep -Milliseconds 100 
} 

請注意,如果您V2你需要@($jobs | Select-Object -Expand State)更換$jobs.State,因爲PowerShell不會自動V3之前展開的屬性訪問陣列還在使用PowerShell的。

+0

感謝您對單個輸出文件參考的提示。手動爲每個服務器調用'Start-Job'並記錄所需的日誌現在按預期工作。但是,當我嘗試在for循環中替換服務器名稱時,作業無法按預期啓動。 'foreach($ servers in $ servers){ Start-Job -Name $ server -ScriptBlock {Get-Content「\\ $ server \ logfile」-Wait -Last 1 |選擇字符串「僅匹配一些文本」| Out-File D:\ $ server.log} }' 我在Win7/5.0 RTM –

+0

爲了能夠在腳本塊中使用腳本其餘部分的變量,您需要將它們作爲參數傳遞在我的代碼示例中)或使用'using:'[scope修飾符](https://technet.microsoft.com/en-us/library/hh847849.aspx)。 –

+0

非常感謝您的幫助,我會檢查一下。 –