2008-08-18 26 views
19

Tương đương với DOS FINDSTR cho PowerShell là gì? Tôi cần tìm kiếm một loạt các tệp nhật ký cho "ERROR".PowerShell FINDSTR eqivalent?

+1

Có một trang web với một bài viết tốt cho việc này: http://www.interact-sw.co.uk/iangblog/2006/06/03/pshfindstr –

Trả lời

23

Đây là câu trả lời nhanh

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

tôi thấy nó here trong đó có một câu trả lời sâu sắc tuyệt vời!

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

Là hướng đối tượng, bạn muốn kiểm tra thuộc tính được đề cập với một trong các toán tử so sánh chuẩn bạn có thể tìm thấy here.

Tôi có PS script xem nhật ký từ xa cho tôi ngay bây giờ - một số sửa đổi đơn giản sẽ làm cho nó hoạt động cho bạn.

chỉnh sửa: Tôi cho rằng tôi cũng nên thêm đó là một lệnh ghép ngắn được xây dựng cho điều này nếu bạn không muốn hủy đăng ký theo cách tôi đã làm. Kiểm tra:

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

Ví dụ: tìm tất cả các phiên bản "#include" trong các tệp c trong thư mục này và tất cả các thư mục con.

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

GCI là một bí danh cho get-childitem

3

Chỉ cần mở rộng về câu trả lời của Monroecheeseman. gci là một bí danh cho Get-ChildItem (tương đương với dir hoặc ls), công tắc -r thực hiện tìm kiếm đệ quy và -i có nghĩa là bao gồm.

Đường ống kết quả của truy vấn đó vào chuỗi chọn có đọc từng tệp và tìm dòng phù hợp với cụm từ thông dụng không (biểu mẫu được cung cấp trong trường hợp này là L ERI, nhưng có thể là bất kỳ biểu thức chính quy .NET nào).

Kết quả sẽ là tập hợp các đối tượng trùng khớp, hiển thị đối sánh đường, tệp và các thông tin liên quan khác.

0

Trên ghi chú liên quan, đây là tìm kiếm sẽ liệt kê tất cả các tệp có chứa chuỗi hoặc tìm kiếm regex cụ thể. Nó có thể sử dụng một số cải tiến để cảm thấy tự do để làm việc trên nó. Ngoài ra nếu ai đó muốn đóng gói nó trong một chức năng mà sẽ được chào đón.

Tôi mới ở đây vì vậy nếu điều này nên đi trong chủ đề riêng của nó chỉ cho tôi biết. Tôi nghĩ tôi sẽ đặt nó cho cô ấy vì điều này hầu như có liên quan.

# 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) {[email protected]{AllMatches=$True}} 
else {[email protected]{List=$True}} 
if ($IncludeSubfolders -eq $True) {[email protected]{Recurse=$True}} 
else {[email protected]{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 
#> 
0

Đây không phải là cách tốt nhất để làm điều này:

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

này đã giúp tôi tìm thấy tất cả các file csv trong đó có nhân vật | trong đó.

0

PowerShell về cơ bản đã loại trừ sự cần thiết cho findstr.exe như các câu trả lời trước đây minh họa. Bất kỳ câu trả lời nào trong số này đều có tác dụng tốt.

Tuy nhiên, nếu bạn thực sự cần sử dụng số findstr.exe (như là trường hợp của tôi) đây là một wrapper PowerShell cho nó:

Sử dụng -Verbose lựa chọn để sản xuất các dòng lệnh findstr.


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 $_ 
      } 
     } 
    } 
} 
Các vấn đề liên quan