12

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!

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326

3 Answers3

14

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.

Moerwald
  • 10,448
  • 9
  • 43
  • 83
  • Yup, this was exactly what I was looking for. Just saw the syntax and never seen it and Google wasn't much help. I just like to learn when I see something I don't know.. – Mike Christensen Jun 04 '19 at 16:10
8

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
2

I suppose by its name, it's intended to be used in a pipeline. I don't see it used much.

PS C:\users\js> Filter plusone { $_ + 1 }
PS C:\users\js> Echo 1 | plusone
2

PS C:\users\js> Filter comma { '{0:n0}' -f $_ }
PS C:\users\js> 1234567890 | comma
1,234,567,890
js2010
  • 23,033
  • 6
  • 64
  • 66