Skip to content

Instantly share code, notes, and snippets.

@pierre3
Last active August 29, 2015 14:07
Show Gist options
  • Save pierre3/828334f4827ade635821 to your computer and use it in GitHub Desktop.
Save pierre3/828334f4827ade635821 to your computer and use it in GitHub Desktop.
[PowerShell] A enumeration cmdlet of delayed evaluation.
function Where-Block
{
[CmdletBinding()]
[OutputType([scriptblock])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[PSObject]
$InputObject,
[Parameter(Mandatory=$true,
Position=1)]
[scriptblock]
$Predicate
)
Begin
{
}
Process
{
foreach($item in $InputObject)
{
return {
if($item -is [scriptblock])
{
$argument = &$item
if($argument -eq $null){ return }
}else
{
$argument = $item
}
[bool]$result = &$Predicate $argument
if($result -eq $true)
{
return $argument
}
}.GetNewClosure()
}
}
End
{
}
}
function Select-Block
{
[CmdletBinding()]
[OutputType([scriptblock])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[PSObject]
$InputObject,
[Parameter(Mandatory=$true,
Position=1)]
[scriptblock]
$Selector
)
Begin
{
}
Process
{
foreach($item in $InputObject)
{
return {
if($item -is [scriptblock])
{
$argument = &$item
if($argument -eq $null){ return }
}else
{
$argument = $item
}
&$Selector $argument
}.GetNewClosure()
}
}
End
{
}
}
function Foreach-Block
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
Position=0)]
[scriptblock[]]
$Sequence,
[Parameter(Position=1)]
[scriptblock]
$Action = $null
)
Begin
{
}
Process
{
foreach($item in $Sequence)
{
$result = &$item
if($result -eq $null) { continue }
if($Action -eq $null)
{
$result
}
else
{
&$Action $result
}
}
}
End
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment