Passing Predicates as Parameters in PowerShell

This is just a quick trick that I figured out today. I had a process that manipulated a dataset, and I needed to be able to change the process to allow me to filter the data that was processed. Also, it wasn’t clear exactly what kind of filter would specifically be needed in any given scenario.

Normally, I would just filter the data using where-object and pass it in to the function in question. The problem here was that the data retrieval was somewhat cumbersome, and I didn’t want to push that complexity outside of the function. And since the filtering criteria wasn’t clear-cut, I couldn’t (and didn’t want to) use a bunch of switches and parameters along with a nest of if/else conditions.

What I wanted, was to pass a predicate (an expression that would evaluate to true or false depending on whether I want a row in the dataset) in to the function. Essentially, I wanted to insert a where-object into the middle of the function.

Amazingly, PowerShell allows me to do that. The code looks a bit strange to me at first, but it works very well and isn’t complicated at all.

Here’s an example:

function process-data{
Param( [scriptblock]$filter = {$true})

	#retrieve the data

	#filter the data
	$data = $data | where-object $filter

	#process the data
}

process-data -filter {$_.UpdatedDateTime -gt (get-date '1/1/2010')}

It’s not earth-shattering, but I think this will come in handy in several places for me.

Let me know what you think.

-Mike