Skip to content

Instantly share code, notes, and snippets.

@SeeminglyScience
Created June 14, 2019 15:49
Show Gist options
  • Save SeeminglyScience/ae3aa639ba49d6bc7e45d00cc63680e3 to your computer and use it in GitHub Desktop.
Save SeeminglyScience/ae3aa639ba49d6bc7e45d00cc63680e3 to your computer and use it in GitHub Desktop.
# Syntax:
# ?? -If $true -Then { 'yep' } -Else { 'nah' }
# ?? -If $true { 'yep' } : { 'nah' }
# ?? -If $true { 'yep' } else { 'nah' }
# ?? -If $true { 'yep' } { 'nah' }
#
# $true | ?? -Then { 'yep' } -Else { 'nah' }
# $true | ?? { 'yep' } : { 'nah' }
# $true | ?? { 'yep' } else { 'nah' }
# $true | ?? { 'yep' } { 'nah' }
#
# @() | ?? { 'nothin' }
# @() | ?? -Else { 'nothin' }
function Invoke-Conditional {
[Alias('??')]
[CmdletBinding(PositionalBinding = $false, DefaultParameterSetName = 'WithDecoration')]
param(
[Parameter(Position = 0)]
[ValidateNotNull()]
[scriptblock] $Then,
[Parameter(DontShow, Position = 1, ParameterSetName = 'WithDecoration')]
[ValidateSet(':', 'else')]
[string] $Decoration,
[Parameter(Position = 2, ParameterSetName = 'WithDecoration')]
[Parameter(Position = 1, ParameterSetName = 'WithoutDecoration')]
[ValidateNotNull()]
[scriptblock] $Else,
[Parameter(ValueFromPipeline)]
[AllowNull()]
[AllowEmptyCollection()]
[psobject] $If
)
begin {
$firstObject = $null
$hasSetFirstObject = $false
$pipelineInputCount = 0
if ($PSBoundParameters.ContainsKey('Then') -and $PSBoundParameters.ContainsKey('Else')) {
$onFalse = $Else
$onTrue = $Then
} elseif ($PSBoundParameters.ContainsKey('Else')) {
$onFalse = $Else
$onTrue = $null
} elseif ($PSBoundParameters.ContainsKey('Then')) {
$onFalse = $Then
$onTrue = $null
} else {
$exception = [System.Management.Automation.PSArgumentException]::new(
'At least one action must be specified. Please specify a value for the ' +
'parameter "Then", "Else", or both and then try the command again')
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
<# exception: #> $exception,
<# errorId: #> 'NoActionSpecified',
<# errorCategory: #> [System.Management.Automation.ErrorCategory]::InvalidArgument,
<# targetObject: #> $null))
return
}
}
process {
if (-not $hasSetFirstObject) {
$firstObject = $If
$hasSetFirstObject = $true
}
$pipelineInputCount++
}
end {
$isTrue = $pipelineInputCount -gt 1 -or ($pipelineInputCount -eq 1 -and $firstObject)
if ($isTrue) {
if ($null -ne $onTrue) {
return . $onTrue
}
return
}
return . $onFalse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment