grep for PowerShell

Line Break

Author: Frank-Peter (77 Articles)

Hello again. This time I will share a small function that resides in my PowerShell profile script: grep. What is grep? grep is a text search utility originally written for Unix. The command name is an abbreviation for “global regular expression print”. The original grep – and my PowerShell grep function as well – searches files for lines matching a given regular expression and displays the matches in standard output.

Here comes the ready for use function…

function grep (
    $File = $(throw "Empty value for the File parameter."),
    $Pattern = $(throw "Empty value for the Pattern parameter."),
    [switch]$Recurse
) {
    if ($Recurse) {
        $Files = @(Get-ChildItem $File -Recurse)
    } else {
        $Files = @(Get-ChildItem $File)
    }
    if ($Files.Count -eq 0) {
        Write-Host "File(s) not found - $File"; return $null
    }
    $Results = $Files | Select-String -Pattern $Pattern
    if (!$Results) {
        Write-Host "No matches found in $File"; return $null
    }
    $Results | Format-List FileName,LineNumber,Line
}

Actually the grep function simplifies the usage of a command line like below:

PS C:\> gci c:\windows\windowsupdate*.log | Select-String "2009-12" | fl FileName,LineNumber,Line

Using grep you just need to type this:

PS C:\> grep -File C:\Windows\WindowsUpdate*.log -Pattern "2009-12"

Ah, almost I forgot to mention that the Select-String cmdlet is PowerShell’s grep.

Bookmark and Share
Tags »

Author:Frank-Peter
Date: Tuesday, 2. February 2010 23:07
Trackback: Trackback-URL Category: General, PowerShell

Feed for the post RSS 2.0 Comment this post

1 Comment

  1. 1

    Nice thanks

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image