PowerShell Извлечение текста между двумя строками с помощью -Tail и -Wait
У меня есть текстовый файл с большим количеством сообщений журнала. Я хочу извлечь сообщения между двумя строковыми шаблонами. Я хочу, чтобы извлеченное сообщение отображалось в текстовом файле.
Я пробовал следующие методы. Он работает, но не поддерживает опции Get-Content -Wait и -Tail. Также извлеченные результаты отображаются в одну строку, а не как текстовый файл. Дополнения приветствуются :-)
Образец кода
function GetTextBetweenTwoStrings($startPattern, $endPattern, $filePath){
# Get content from the input file
$fileContent = Get-Content $filePath
# Regular expression (Regex) of the given start and end patterns
$pattern = "$startPattern(.*?)$endPattern"
# Perform the Regex opperation
$result = [regex]::Match($fileContent,$pattern).Value
# Finally return the result to the caller
return $result
}
# Clear the screen
Clear-Host
$input = "THE-LOG-FILE.log"
$startPattern = 'START-OF-PATTERN'
$endPattern = 'END-OF-PATTERN'
# Call the function
GetTextBetweenTwoStrings -startPattern $startPattern -endPattern $endPattern -filePath $input
Улучшенный сценарий на основе ответа Тео. Необходимо улучшить следующие моменты:
- Начало и конец вывода каким-то образом обрезаны, несмотря на то, что я настроил размер буфера в скрипте.
- Как обернуть каждый совпадающий результат в строку START и END?
- Тем не менее, я не мог понять, как использовать
-Wait
и-Tail
параметры
Обновленный скрипт
# Clear the screen
Clear-Host
# Adjust the buffer size of the window
$bw = 10000
$bh = 300000
if ($host.name -eq 'ConsoleHost') # or -notmatch 'ISE'
{
[console]::bufferwidth = $bw
[console]::bufferheight = $bh
}
else
{
$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = $bh
$newsize.width = $bw
$pswindow.buffersize = $newsize
}
function Get-TextBetweenTwoStrings ([string]$startPattern, [string]$endPattern, [string]$filePath){
# Get content from the input file
$fileContent = Get-Content -Path $filePath -Raw
# Regular expression (Regex) of the given start and end patterns
$pattern = '(?is){0}(.*?){1}' -f [regex]::Escape($startPattern), [regex]::Escape($endPattern)
# Perform the Regex operation and output
[regex]::Match($fileContent,$pattern).Groups[1].Value
}
# Input file path
$inputFile = "THE-LOG-FILE.log"
# The patterns
$startPattern = 'START-OF-PATTERN'
$endPattern = 'END-OF-PATTERN'
Get-TextBetweenTwoStrings -startPattern $startPattern -endPattern $endPattern -filePath $inputFile