Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the filter keyword do in PowerShell?

Tags:

powershell

I ran across some Powershell code using the filter command. I've never seen this command, but it works basically like this:

enter image description here

It seems to behave as a function. If I run Get-Command filter I get back The term 'filter' is not recognized as the name of a cmdlet, function, script file, or operable program. and Get-Alias filter also returns a similar message. Get-Help filter just returns Cmdlets and Functions with the word Filter somewhere. If I Google for "Powershell filter command", I just get a bunch of stuff about various commands with -Filter arguments and Where-Object syntax.

What is this command and what is it used for? Is there documentation on it somewhere? Thanks!

like image 754
Mike Christensen Avatar asked Jun 04 '19 15:06

Mike Christensen


2 Answers

In short, a filter is a function only able to use the process-block. Based on that in can be used to manipulate (filter, modify...) pipeline objects. They also allow you to e. g. deliver pre defined filter function with a module, saving you the work of writing complicated Where-Objects script blocks 100 of times.

about functions

Filters

A filter is a type of function that runs on each object in the pipeline. A filter resembles a function with all its statements in a Process block. The following filter takes log entries from the pipeline and then displays either the whole entry or only the message portion of the entry:

 filter Get-ErrorLog ([switch]$message)
 {
   if ($message) { Out-Host -InputObject $_.Message }
   else { $_ }
 }

This link offers good explanation about including some examples.

Hope that helps.

like image 144
Moerwald Avatar answered Nov 02 '22 15:11

Moerwald


A filter definition is syntactic sugar that makes it easier to create parameter-less functions whose sole purpose is to process input from the pipeline, (the latter being represented by the automatic $_ variable), but without the need to explicitly declare a process block that ensures per-input-object invocation.

That is, for example:

filter Add-One { 1 + $_ }

is syntactic sugar for:

function Add-One { process { 1 + $_ } }

With either definition, the following sample command:

1, 2 | Add-One

would yield:

2
3

Perhaps because of their limitations - no (easy) support for parameters, no support for invocation with -?, ... - and the limited syntactic convenience they afford, filters aren't widely used.

like image 39
mklement0 Avatar answered Nov 02 '22 15:11

mklement0