Skip to content

Instantly share code, notes, and snippets.

@christian-korneck
Last active April 14, 2024 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christian-korneck/1e108164ace0848085282234e41351c7 to your computer and use it in GitHub Desktop.
Save christian-korneck/1e108164ace0848085282234e41351c7 to your computer and use it in GitHub Desktop.
Unix-like destructive grep in Powershell

Powershell pure text grep (grepp)

what

A grep command (grepp) in Powershell that lets you grep for a string in the text that would usually be printed in the terminal (not some other representation of the data). Output is a string, not a pipeline anymore - thus destructive.

why

To quickly grep through shell output without having to do where-object gymnastics.

install

put this i.e. in your $profile file.

function grepp {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [Object]$InputObject,

        [Parameter(Position = 0)]
        [string]$GrepString
    )

    begin {
        $objects = [System.Collections.Generic.List[object]]::new()
    }

    process {
        $objects.Add($InputObject)
    }

    end {
        ($objects | Out-String) -split "`n" | select-string $GrepString
    }
}

(special thanks to @chrisdent from powershell slack for helping to figure this out)

usage examples

example 1

to quickly find out what aliases exist for where-object you'd usually do something like:

PS> get-alias | Where-Object Displayname -like *where-object*

This requires you to

  • find out what property to filter on (i.e. with something like get-alias | select -property * -first 1 and/or get-alias | get member, etc).
  • figure out what operator you need and write an expression for it (hint: -contains where-object doesn't work)

with grepp this becomes less thinking and muscle memory instead:

PS> get-alias | grepp where-object

Alias           ? -> Where-Object
Alias           where -> Where-Object

example 2: multiple uses chained

PS> Get-Process | Select-Object -Property CommandLine -ExpandProperty CommandLine | grepp windows | grepp system32

C:\Windows\system32\DllHost.exe /Processid:{AB8902B4-09CA-4BB6-B78D-A8F59079A8D5}
"C:\Windows\system32\notepad.exe" C:\Users\user\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
C:\Windows\System32\RuntimeBroker.exe -Embedding
...

example 3: grep in all streams (not just success/stdout )

PS> & { write-host helloo; Write-Warning oops } *>&1 | grepp oo
helloo
oops
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment