Last active
August 25, 2017 19:08
-
-
Save sean-m/f13fddaf228aa3db9087c1b20a937987 to your computer and use it in GitHub Desktop.
My take on a ternary operation for PowerShell, I use it for my stuff and make no promises. Enjoy!
This file contains hidden or 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
<# | |
.Synopsis | |
Ternary operation for PowerShell with terse | |
parameter aliases. Meant to be used from pipeline. | |
.Example | |
gci -Recurse | >> {$_.PSIsContainer} "Directory" "File" | |
.Example | |
1..10 | >> {($_ % 2) -eq 0} "Even" "Odd" | |
.Example | |
# Pass through numbers greater than 0 or print 0 | |
$random_number_list | >> {$_ -gt 0} {$_} 0 | |
.Example | |
# Nested expressions must qualify the predicate input variable | |
gci | >> {$_.PSIsContainer} "Directory" {>> {param($i) $i -lt 8192} "SmallFile" "BigFile" ($_.Length)} | |
#> | |
function Ternary | |
{ | |
[CmdletBinding()] | |
[Alias(">>")] | |
Param | |
( | |
[Parameter(Mandatory=$true, | |
ValueFromPipeline=$false, | |
Position=0)] | |
[Alias("P")] | |
[ScriptBlock]$Predicate, | |
[Parameter(Mandatory=$true, | |
ValueFromPipeline=$false, | |
Position=1)] | |
[Alias("T")] | |
$Expr1, | |
[Parameter(Mandatory=$true, | |
ValueFromPipeline=$false, | |
Position=2)] | |
[Alias("F")] | |
$Expr2, | |
# Param1 help description | |
[Parameter(Mandatory=$false, | |
ValueFromPipeline=$true, | |
Position=3)] | |
$InputObj | |
) | |
Process | |
{ | |
if ([bool]($Predicate.Invoke($InputObj))) { | |
if ($Expr1.GetType().Name -like 'ScriptBlock') { $Expr1.Invoke($InputObj) } | |
else { $Expr1 } | |
} | |
else { | |
if ($Expr2.GetType().Name -like 'ScriptBlock') { | |
$Expr2.Invoke($InputObj) | |
} | |
else { $Expr2 } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment