programing

PowerShell FINDSTR과 동등합니까?

elecom 2023. 8. 21. 19:36
반응형

PowerShell FINDSTR과 동등합니까?

PowerShell의 DOS FINDSTR과 동등한 기능은 무엇입니까?로그 파일에서 "ERROR"를 검색해야 합니다.

여기 빠른 대답이 있습니다.

Get-ChildItem -Recurse -Include *.log | select-string ERROR 

나는 여기서 그것을 찾았는데, 그것은 매우 심오한 답을 가지고 있습니다!

예를 들어 이 디렉터리의 c 파일과 모든 하위 디렉터리에서 "#include"의 모든 인스턴스를 찾습니다.

gci -r -i *.c | select-string "#include"

gci는 get-child 항목의 별칭입니다.

먼로 치즈맨의 답변을 확장하기 위해. gci는 Get-ChildItem(디렉터와 동일)의 별칭입니다. -r 스위치는 재귀 검색을 수행하며 -i는 다음을 포함합니다.

해당 쿼리의 결과를 select-string으로 파이프하면 각 파일을 읽고 정규식과 일치하는 행을 찾습니다(이 경우 제공된 행은 ERROR이지만 any일 수 있습니다).NET 정규식).

결과적으로 일치하는 객체의 집합이 되고, 일치하는 선, 파일 및 기타 관련 정보가 표시됩니다.

if ($entry.EntryType -eq "Error")

개체 지향적인 경우 여기에서 찾을 수 있는 표준 비교 연산자 중 하나를 사용하여 해당 속성을 테스트하려고 합니다.

지금 원격으로 로그를 모니터링하는 PS 스크립트가 있습니다. 간단한 수정을 통해 사용자에게 도움이 될 수 있습니다.

편집: 만약 당신이 제가 했던 방식을 해제하고 싶지 않다면, 저는 이미 이것을 위해 만들어진 cmdlet도 추가해야 한다고 생각합니다.체크아웃:

man Get-EventLog
Get-EventLog -newest 5 -logname System -EntryType Error

관련하여 특정 정규식 검색 또는 문자열이 포함된 모든 파일을 나열하는 검색이 있습니다.개선이 필요할 수 있으니 편하게 작업하세요.또한 누군가가 그것을 기능으로 캡슐화하고 싶어한다면 환영할 것입니다.

저는 이곳에 온 지 얼마 안 됐는데, 만약 이것이 독자적인 주제로 다뤄진다면 저에게 알려주세요.이 일이 대부분 관련이 있는 것처럼 보이니까 그녀를 넣으려고 했어요.

# Search in Files Script
# ---- Set these before you begin ---- 
$FolderToSearch="C:\" # UNC paths are ok, but remember you're mass reading file contents over the network
$Search="Looking For This" # accepts regex format
$IncludeSubfolders=$True #BUG: if this is set $False then $FileIncludeFilter must be "*" or you will always get 0 results
$AllMatches=$False
$FileIncludeFilter="*".split(",") # Restricting to specific file types is faster than excluding everything else
$FileExcludeFilter="*.exe,*.dll,*.wav,*.mp3,*.gif,*.jpg,*.png,*.ghs,*.rar,*.iso,*.zip,*.vmdk,*.dat,*.pst,*.gho".split(",")

# ---- Initialize ----
if ($AllMatches -eq $True) {$SelectParam=@{AllMatches=$True}}
else {$SelectParam=@{List=$True}}
if ($IncludeSubfolders -eq $True) {$RecurseParam=@{Recurse=$True}}
else {$RecurseParam=@{Recurse=$False}}

# ---- Build File List ---- 
#$Files=Get-Content -Path="$env:userprofile\Desktop\FileList.txt" # For searching a manual list of files
Write-Host "Building file list..." -NoNewline
$Files=Get-ChildItem -Include $FileIncludeFilter -Exclude $FileExcludeFilter -Path $FolderToSearch -ErrorAction silentlycontinue @RecurseParam|Where-Object{-not $_.psIsContainer} # @RecurseParam is basically -Recurse=[$True|$False]
#$Files=$Files|Out-GridView -PassThru -Title 'Select the Files to Search' # Manually choose files to search, requires powershell 3.0
Write-Host "Done"

# ---- Begin Search ---- 
Write-Host "Searching Files..."
$Files|
    Select-String $Search @SelectParam| #The @ instead of $ lets me pass the hastable as a list of parameters.  @SelectParam is either -List or -AllMatches
    Tee-Object -Variable Results|
    Select-Object Path
Write-Host "Search Complete"
#$Results|Group-Object path|ForEach-Object{$path=$_.name; $matches=$_.group|%{[string]::join("`t", $_.Matches)}; "$path`t$matches"} # Show results including the matches separated by tabs (useful if using regex search)

<# Other Stuff
    #-- Saving and restoring results
    $Results|Export-Csv "$env:appdata\SearchResults.txt" # $env:appdata can be replaced with any UNC path, this just seemed like a logical place to default to
    $Results=Import-Csv "$env:appdata\SearchResults.txt"

    #-- alternate search patterns
    $Search="(\d[-|]{0,}){15,19}" #Rough CC Match
#>

이렇게 하는 것이 가장 좋은 방법은 아닙니다.

gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains("|") -eq $true }

이를 통해 다음이 포함된 모든 CSV 파일을 찾는 데 도움이 되었습니다.|그 안에 있는 인격.

PowerShell은 이전 답변에서 보여주었듯이 findstr.exe가 필요하지 않습니다.다음 답변 중 하나라도 제대로 작동합니다.

그러나 실제로 findstr.exe 사용해야 하는 경우(제 경우와 마찬가지로) PowerShell 래퍼가 있습니다.

사용-Verbosefindstr 명령행을 출력하는 옵션입니다.


function Find-String
{
    [CmdletBinding(DefaultParameterSetName='Path')]
    param
    (
        [Parameter(Mandatory=$true, Position=0)]
        [string]
        $Pattern,

        [Parameter(ParameterSetName='Path', Mandatory=$false, Position=1, ValueFromPipeline=$true)]
        [string[]]
        $Path,

        [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
        [Alias('PSPath')]
        [string[]]
        $LiteralPath,

        [Parameter(Mandatory=$false)]
        [switch]
        $IgnoreCase,

        [Parameter(Mandatory=$false)]
        [switch]
        $UseLiteral,

        [Parameter(Mandatory=$false)]
        [switch]
        $Recurse,

        [Parameter(Mandatory=$false)]
        [switch]
        $Force,

        [Parameter(Mandatory=$false)]
        [switch]
        $AsCustomObject
    )

    begin
    {
        $value = $Pattern.Replace('\', '\\\\').Replace('"', '\"')

        $findStrArgs = @(
            '/N'
            '/O'
            @('/R', '/L')[[bool]$UseLiteral]
            "/c:$value"
        )

        if ($IgnoreCase)
        {
            $findStrArgs += '/I'
        }

        function GetCmdLine([array]$argList)
        {
            ($argList | foreach { @($_, "`"$_`"")[($_.Trim() -match '\s')] }) -join ' '
        }
    }

    process
    {
        $PSBoundParameters[$PSCmdlet.ParameterSetName] | foreach {
            try
            {
                $_ | Get-ChildItem -Recurse:$Recurse -Force:$Force -ErrorAction Stop | foreach {
                    try
                    {
                        $file = $_
                        $argList = $findStrArgs + $file.FullName

                        Write-Verbose "findstr.exe $(GetCmdLine $argList)"

                        findstr.exe $argList | foreach {
                            if (-not $AsCustomObject)
                            {
                                return "${file}:$_"
                            }

                            $split = $_.Split(':', 3)

                            [pscustomobject] @{
                                File = $file
                                Line = $split[0]
                                Column = $split[1]
                                Value = $split[2]
                            }
                        }
                    }
                    catch
                    {
                        Write-Error -ErrorRecord $_
                    }
                }
            }
            catch
            {
                Write-Error -ErrorRecord $_
            }
        }
    }
}

참고로 파워셸 버전 7로 업데이트하면 grep을 사용할 수 있습니다...애저 CLI에서 egrep이 파워셸에 있다는 것을 압니다...하지만 SS는 거기에 있습니다!여기 오래된 기사: [https://devblogs.microsoft.com/powershell/select-string-and-grep/ ]

언급URL : https://stackoverflow.com/questions/14708/powershell-findstr-eqivalent

반응형