Home > front end >  Adding Arguments to PowerShell Alias Functions
Adding Arguments to PowerShell Alias Functions

Time:01-24

I just installed grep on PowerShell through chocolatey and using it, I could search for a string I want from any text as shown below:

enter image description here

However, I don't want to always have to type grep --color, hence I tried to make an alias on my $profile like this:

Function grep($a1){
  grep --color $a1
}

but then I would get an error:

enter image description here

So I tried:

Set-Alias grep "grep --color"

but then I get yet another error:

enter image description here

I can't think of anything else to make this work, hence I'd really appreciate any help.

CodePudding user response:

Aliases in PowerShell are mere alternative names for other commands, so you cannot use them to include arguments to pass to these other commands.

You therefore indeed need a function, but since you're naming it the same as the external program you're wrapping, you need to disambiguate so as to avoid an infinite recursion:

function grep {
  $externalGrep = Get-Command -Type Application grep
  if ($MyInvocation.ExpectingInput) { # pipeline (stdin) input present
    # $args passes all arguments through.
    $input | & $externalGrep --color $args
  } else {
    & $externalGrep --color $args
  }
}

Note:

  • Use of the automatic $input variable to relay pipeline (stdin) input means that this input is collected (buffered) in full first. More effort is needed to implement a true streaming solution - see this answer for an example.

Alternatively - at least on Unix-like platforms - you can set an environment variable to control grep's coloring behavior, which may obviate the need for a function wrapper; the equivalent of the --color parameter is to set $env:GREP_COLOR='always' (the other supported values are 'never' and 'auto').

  •  Tags:  
  • Related