簡體   English   中英

如何在Powershell中為特定字符串尾部日志文件

[英]How to tail log files in Powershell for particular string

我們想在Powershell中為特定字符串尾部添加幾個“活動”的日志文件。 我們嘗試使用“ get-content”命令,但是沒有運氣,因為每次結果我們只收到一個文件的結果。 我認為這是由“ -wait”參數引起的。 是否還有其他方法可以拖尾多個文件? 我聽說過運行空間,但我仍然不知道如何實現它。

我們的示例腳本如下

dir d:\test\*.txt -include *.txt | `
Get-Content -Wait | `
select-string "windows" | `
ForEach-Object {Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $_}

任何幫助將不勝感激。

我能想到的唯一方法是創建一堆在每個文件上運行命令的作業。 然后,您可以循環接收作業輸出,並且任何文件中的更改都將寫入屏幕:

gci d:\test\*.txt | % { $sb = [scriptblock]::create("get-content -wait $_") ; start-job -ScriptBlock $sb }
while(1) { 
  $m = $(get-job | receive-job | select-string "searchstring") 
  if($m -ne $null) { 
     Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $m
  }
  sleep 1 
}

參加聚會可能會有點遲。

按照這里 ,我們可以在.ps1文件中使用以下內容:

$ProgressPreference='SilentlyContinue'
Workflow My-Tail
{
    Param([string[]] $Path)

    foreach -parallel ($file in $path)
    {
        Get-Content -Path $file -Tail 1 -Wait
    }
}

這使我們可以拖尾多個文件,像在powershell中那樣調用;

My-Tail (dir C:\Users\User\Documents\*.log)

剩下的就是根據所需的字符串進行過濾;

My-Tail (dir C:\Users\User\Documents\*.log) | Select-String -Pattern ".*ERROR.*"

這將尾隨文檔中所有以.log結尾的文件,輸出包含文本“ ERROR”的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM