2008-08-18 72 views

回答

23

這裏的快速回答

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

我發現它here其中有一個很大的深入的答案!

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

正在面向對象的,你想用標準比較運算符你可以找到here的一個測試有關財產。

我有一個PS script遠程監視日誌我現在 - 一些簡單的修改應該使它爲你工作。

編輯:我想我還應該補充說,如果你不想按照我的方式展開,那麼就是爲此構建的cmdlet。退房:

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

例如,在此目錄中的c文件和所有子目錄中查找「#include」的所有實例。

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

GCI是GET-childitem

3

只是對Monroecheeseman的回答擴大的別名。 gci是Get-ChildItem的別名(相當於dir或ls),-r開關執行遞歸搜索,-i代表include。

將該查詢的結果管道化爲select-string,它讀取每個文件並查找與正則表達式匹配的行(本例中提供的行是ERROR,但它可以是任何.NET正則表達式)。

結果將是匹配對象的集合,顯示行匹配,文件和其他相關信息。

0

在相關說明中,這裏是一個搜索,它將列出包含特定正則表達式搜索或字符串的所有文件。它可以使用一些改進,所以隨時可以使用它。另外如果有人想將它封裝在一個值得歡迎的函數中。

我在這裏是新的,所以如果這應該在它自己的話題只是讓我知道。我想我會把它放在她身上,因爲這看起來大部分都是相關的。

# 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

這不是做到這一點的最好辦法:

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

幫我找到它有|字符,將它們所有CSV文件。

0

PowerShell已基本排除findstr.exe的需要,如前面的答案所示。任何這些答案都應該可以正常工作。

但是,如果您實際上需要使用findstr,則需要使用。EXE(因爲是我的情況),這裏是一個PowerShell的包裝吧:

使用-Verbose選項輸出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 $_ 
      } 
     } 
    } 
}