Windows Powershell에서의 Unix tail 등가 명령어
큰 파일의 마지막 몇 줄(일반적인 크기는 500MB~2GB)을 확인해야 합니다. 명령어 Unix와 한 명령어를 찾고 .tail
Windows Powershell 。 가지
http://tailforwin32.sourceforge.net/
그리고.
Get-Content [ filename ]| Select-Object - 마지막 10
나로서는 첫 번째 대안을 사용할 수 없고 두 번째 대안도 느리다.PowerShell의 효율적인 테일 구현에 대해 알고 계신 분?
하다를 사용하세요.-wait
[ Get - Content ]알겠습니다.이 기능은 PowerShell v1에는 있었지만 어떤 이유로 v2에서는 제대로 문서화되어 있지 않습니다.
여기 예가 있습니다.
Get-Content -Path "C:\scripts\test.txt" -Wait
이 작업을 실행하면 파일을 업데이트하고 저장하면 콘솔에 변경 내용이 표시됩니다.
완전성을 위해 Powershell 3.0은 Get-Content에 -Tail 플래그가 붙어 있습니다.
Get-Content ./log.log -Tail 10
파일의 마지막 10 행을 가져옵니다.
Get-Content ./log.log -Wait -Tail 10
파일의 마지막 10 행을 취득하여 추가 대기
또한 이러한 *nix 사용자의 경우 대부분의 시스템이 Get-Content에 cat 에일리어스를 붙이기 때문에 보통 이 기능이 작동합니다.
cat ./log.log -Tail 10
PowerShell 버전 3.0부터는 Get-Content cmdlet에 도움이 되는 -Tail 매개 변수가 있습니다.컨텐츠의 취득에 대해서는, technet 라이브러리의 on-line help를 참조해 주세요.
여기 있는 답을 몇 개 썼는데그걸 미리 알려드릴게요
Get-Content -Path Yourfile.log -Tail 30 -Wait
조금 있으면 추억이 깨질 거예요.지난 날 동료가 이런 '테일'을 남겼는데 800MB까지 올라갔어요.유닉스 테일도 같은 방식으로 동작하는지는 모르겠지만 의심스럽네요.그래서 단기 어플리케이션으로 사용해도 괜찮지만 주의하세요.
PSCX(PowerShell Community Extensions)는 cmdlet을 제공합니다.작업에 적합한 솔루션인 것 같습니다.주의: 매우 큰 파일에서는 시도하지 않았습니다만, 설명에 의하면, 내용을 효율적으로 추적해, 큰 로그 파일용으로 설계되어 있습니다.
NAME
Get-FileTail
SYNOPSIS
PSCX Cmdlet: Tails the contents of a file - optionally waiting on new content.
SYNTAX
Get-FileTail [-Path] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]
Get-FileTail [-LiteralPath] <String[]> [-Count <Int32>] [-Encoding <EncodingParameter>] [-LineTerminator <String>] [-Wait] [<CommonParameters>]
DESCRIPTION
This implentation efficiently tails the cotents of a file by reading lines from the end rather then processing the entire file. This behavior is crucial for ef
ficiently tailing large log files and large log files over a network. You can also specify the Wait parameter to have the cmdlet wait and display new content
as it is written to the file. Use Ctrl+C to break out of the wait loop. Note that if an encoding is not specified, the cmdlet will attempt to auto-detect the
encoding by reading the first character from the file. If no character haven't been written to the file yet, the cmdlet will default to using Unicode encoding
. You can override this behavior by explicitly specifying the encoding via the Encoding parameter.
대답하기엔 너무 늦었지만, 이걸 시도해봐.
Get-Content <filename> -tail <number of items wanted> -wait
이전 답변에 추가된 내용입니다.를 들어 UNIX에 Get-Content를 사용할 수 .cat
, , , , , , , , 이 .type
★★★★★★★★★★★★★★★★★」gc
★★★★★★★★★★★★★★★★★★★★★
Get-Content -Path <Path> -Wait -Tail 10
쓸 수 있다
# Print whole file and wait for appended lines and print them
cat <Path> -Wait
# Print last 10 lines and wait for appended lines and print them
cat <Path> -Tail 10 -Wait
Powershell V2 이하에서는 get-content가 파일 전체를 읽기 때문에 아무 소용이 없었습니다.문자 인코딩에 문제가 있을 수 있지만, 다음 코드는 제가 필요로 하는 것에 도움이 됩니다.이것은 사실상 tail -f이지만, 마지막 x 바이트를 얻도록 쉽게 변경할 수 있습니다.줄 바꿈을 거꾸로 검색하려면 마지막 x 행을 얻도록 쉽게 변경할 수 있습니다.
$filename = "\wherever\your\file\is.txt"
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($filename, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length
while ($true)
{
Start-Sleep -m 100
#if the file size has not changed, idle
if ($reader.BaseStream.Length -eq $lastMaxOffset) {
continue;
}
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
대부분의 코드를 여기서 찾았습니다.
@hajamie의 용액을 조금 더 편리한 스크립트 포장지로 포장했습니다.
파일 종료 전 오프셋부터 시작하는 옵션을 추가했기 때문에 파일 종료부터 일정량을 읽을 수 있는 테일 기능을 사용할 수 있습니다.오프셋은 줄이 아닌 바이트 단위입니다.
더 많은 콘텐츠를 계속 기다리는 옵션도 있습니다.
예(이것을 TailFile.ps1 로 보존하고 있는 것을 전제로 합니다).
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000
.\TailFile.ps1 -File .\path\to\myfile.log -InitialOffset 1000000 -Follow:$true
.\TailFile.ps1 -File .\path\to\myfile.log -Follow:$true
그리고 여기 대본이 있습니다.
param (
[Parameter(Mandatory=$true,HelpMessage="Enter the path to a file to tail")][string]$File = "",
[Parameter(Mandatory=$true,HelpMessage="Enter the number of bytes from the end of the file")][int]$InitialOffset = 10248,
[Parameter(Mandatory=$false,HelpMessage="Continuing monitoring the file for new additions?")][boolean]$Follow = $false
)
$ci = get-childitem $File
$fullName = $ci.FullName
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($fullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length - $InitialOffset
while ($true)
{
#if the file size has not changed, idle
if ($reader.BaseStream.Length -ge $lastMaxOffset) {
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
if($Follow){
Start-Sleep -m 100
} else {
break;
}
}
저는 이 주제에 대해 여러 파일에 대한 유용한 팁을 가지고 있습니다.
PowerShell 5.2(Win7 및 Win10)에서 단일 로그 파일(Linux의 'tail -f' 등)을 사용하는 것은 간단합니다('Get-Content MyFile -Tail 1 -Wait' 사용).그러나 여러 로그 파일을 한 번에 보는 것은 복잡한 것 같습니다.PowerShell 7.x+에서는 "Foreach-Object - Parallel"을 사용하여 간단한 방법을 찾았습니다.그러면 여러 'Get-Content' 명령이 동시에 수행됩니다.예를 들어 다음과 같습니다.
Get-ChildItem C:\logs\*.log | Foreach-Object -Parallel { Get-Content $_ -Tail 1 -Wait }
해라Windows Server 2003 Resource Kit Tools
이 파일에는tail.exe
Windows 시스템에서 실행할 수 있습니다.
https://www.microsoft.com/en-us/download/details.aspx?id=17657
지금까지 유효한 답변이 많이 있었습니다만, 어느 것도 Linux의 tail과 같은 구문을 가지고 있지 않습니다.다음 기능을 저장할 수 있습니다.$Home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
영속성에 대해서는 (자세한 내용은 powershell 프로파일의 매뉴얼을 참조해 주세요).
이렇게 하면 전화...
tail server.log
tail -n 5 server.log
tail -f server.log
tail -Follow -Lines 5 -Path server.log
Linux 구문에 매우 가깝습니다.
function tail {
<#
.SYNOPSIS
Get the last n lines of a text file.
.PARAMETER Follow
output appended data as the file grows
.PARAMETER Lines
output the last N lines (default: 10)
.PARAMETER Path
path to the text file
.INPUTS
System.Int
IO.FileInfo
.OUTPUTS
System.String
.EXAMPLE
PS> tail c:\server.log
.EXAMPLE
PS> tail -f -n 20 c:\server.log
#>
[CmdletBinding()]
[OutputType('System.String')]
Param(
[Alias("f")]
[parameter(Mandatory=$false)]
[switch]$Follow,
[Alias("n")]
[parameter(Mandatory=$false)]
[Int]$Lines = 10,
[parameter(Mandatory=$true, Position=5)]
[ValidateNotNullOrEmpty()]
[IO.FileInfo]$Path
)
if ($Follow)
{
Get-Content -Path $Path -Tail $Lines -Wait
}
else
{
Get-Content -Path $Path -Tail $Lines
}
}
매우 기본이지만 애드온 모듈이나 PS 버전 요건 없이 필요한 기능을 제공합니다.
while ($true) {Clear-Host; gc E:\test.txt | select -last 3; sleep 2 }
Windows용으로 컴파일된 모든 UNIX 명령어는 다음 GitHub 저장소에서 다운로드할 수 있습니다.https://github.com/George-Ogden/UNIX
타이핑을 적게 하는 것이 최선이라는 원칙에 입각한 관리자를 위해 제가 찾을 수 있는 가장 짧은 버전은 다음과 같습니다.
gc filename -wai -ta 10
언급URL : https://stackoverflow.com/questions/4426442/unix-tail-equivalent-command-in-windows-powershell
'programing' 카테고리의 다른 글
Swift에서 문자열을 Base64로 인코딩하려면 어떻게 해야 하나요? (0) | 2023.04.13 |
---|---|
C#에서 SQL 쿼리를 직접 실행하는 방법 (0) | 2023.04.13 |
n행부터 마지막행까지의 합계 (0) | 2023.04.13 |
'컷'을 사용하여 마지막 필드를 찾는 방법 (0) | 2023.04.13 |
키 목록을 통해 중첩된 사전 항목에 액세스하시겠습니까? (0) | 2023.04.13 |