Last active
August 29, 2015 14:07
-
-
Save pierre3/828334f4827ade635821 to your computer and use it in GitHub Desktop.
[PowerShell] A enumeration cmdlet of delayed evaluation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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