forked from alx9r/ToolFoundations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
invoke.ps1
61 lines (50 loc) · 1.74 KB
/
invoke.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# This module is derived from Richard Berg's Invoke-IfScriptBlock.ps1 and Invoke-Ternary.ps1 modules:
# http://tfstoys.codeplex.com/SourceControl/changeset/view/33350#Modules/RichardBerg-Misc
Set-Alias ?: Invoke-Ternary
function Invoke-Ternary
{
<#
.SYNOPSIS
If Condition gets coerced to True, emit Primary, otherwise Alternate.
.DESCRIPTION
The only things that should fail the test are:
(1) a boolean whose value is False
(2) an empty collection
(3) a collection whose last value is boolean false
(4) null
Primary and Alternate can be wrapped in scriptblocks if you need delayed execution.
Obviously there is similarity between Invoke-Coalescing and -Ternary. It's mainly just syntax. Both functions are designed to look like the corresponding operators in C-style languages by using the pipeline to simulate infix notation. (functions are usually prefix, and you can't define your own operators in Powershell) Pipeline-based construction also allows them to be chained together in interesting [but different] ways.
.EXAMPLE
1 + 1 -eq 2 | ?: "yay" "new math"
.EXAMPLE
get-process asdfjkl* | ?: {$null.TotallyIllegal()} {"Ok"}
.EXAMPLE
# a puzzle - don't cheat
$false, $true | ?: $false $true | ?: $false $true | ?: $false $true | ?: $false $true
#>
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$True)]
[object]$Condition,
[parameter(Position=0)]
[object]$Primary,
[parameter(Position=1)]
[object]$Alternate
)
end
{
if ($Condition)
{ Invoke-IfScriptBlock $Primary }
else
{ Invoke-IfScriptBlock $Alternate }
}
}
function Invoke-IfScriptBlock($object)
{
if ($object -is [scriptblock]) {
& $object
}
else {
$object
}
}