IIf (Inline If)

The Inline If (IIf, see also: ternary If) is probably the smallest cmdlet that you will find on this powersnippets.com site although it has grown overtime (see: IIf on StackOverflow) to support some extra features as expressions and reusing the conditional object.

Cmdlet

Syntax

If [-Condition] <Expression> [-IfTrue] <Object|ScriptBlock>&nbsp;[[-IfFalse] <Object|ScriptBlock>]

Parameters

[-Condition] <Expression>

Required. An expression that can be evaluated to a Boolean.

[-IfTrue] <Object|ScriptBlock>

Required. Object or ScriptBlock. If an object is supplied, it will be returned if Expression evaluates to True. If an ScriptBlock is supplied, it will be evaluated if Expression evaluates to True.

[[-IfFalse] <Object|ScriptBlock>]

Optional. Object or ScriptBlock. If an object is supplied, it will be returned if Expression evaluates to False. If an ScriptBlock is supplied, it will be evaluated if Expression evaluates to False. If the parameter is omitted, a $Null will be returned if Expression evaluates to False.

Examples

IIf $a {1/$a} NaN

Or placed inline:

"The multiplicative inverse of $a is $(IIf $a {1/$a} NaN)."

In case $a has a value other than zero, the multiplicative inverse is returned, otherwise it will return NaN (where the {1/$a} is not evaluated).

Another nice example where it will make a quiet ambiguous syntax a lot simpler (especially in case you want to place it inline) is where you want to run a method on an object which could potentially be $Null. The native ‘If’ way to do this, would be something like this:

If ($Object) {$a = $Object.Method()} Else {$a = $null}

(Note that the Else part is often required in e.g. loops where you will need to reset $a.). With the IIf cmdlet it will look like this:

$a = IIf $Object {$_.Method()}

Note that if the $Object is $Null$a will automatically be set to $Null if no $IfFalse value is supplied.

Also note that if the expression parameter is not a Boolean type, it will be available as the current object $_ (or $PSItem) in the IfTrue ScriptBlock which could make a verbose command a lot easier. Take e.g.:

$VolatileEnvironment = Get-Item -ErrorAction SilentlyContinue "HKCU:\Volatile Environment" $UserName = IIf $VolatileEnvironment {$_.GetValue("UserName")}

Normally, the command $VolatileEnvironment.GetValue("UserName") results in an “You cannot call a method on a null-valued expression.” error if the concerned registry (HKCU:\Volatile Environment) doesn’t exist, where the command IIf $VolatileEnvironment {$_.GetValue("UserName")} will just return $Null.

To prevent that the current object of the parent function is overruled, force the -Condition parameter to a Boolean (with the [Bool] type, e.g. -Condition [Bool]$Object).

The IIf (Inline If) cmdlet was originally published at StackOverflow