Here's a little PowerShell script that acts as a coalescing pipeline filter:
param( [scriptblock] $predicate={ $_ } )
begin
{
$script:found = $false;
$script:item = $null;
}
process
{
if( ! $script:found -and ( &$predicate ) )
{
$script:found = $true;
$script:item = $_;
}
}
end
{
return $script:item;
}
When used as a pipeline filter, this script returns the first non-null object coming out of the executing pipeline. Here's a simple example:
$value = @( $null, "first", "second" ) | coalesce;
The result of this script is that $value is equal to "first". I find myself using this quite a bit for things like default values for optional parameters:
param( $p1, $p2 );
$value = @( $p1, $p2, "defaultValue" ) | coalesce;
The $predicate parameter allows you to pass in your own criteria as a script block; e.g.:
$p1 = @( $a, $b, $c ) | coalesce { $_ -gt 1 };
will return the first value from the list greater than 1.
Looks a lot like the where-object filter, except that coalesce returns only the first object from the pipeline matching the specified criteria.
Enjoy!