Below is a Ternary Operator (?: in C or IIF in VB) implementation in Powershell, inspired by this post.
This is a most close enough form of ?: Or Ternary Operator in Powershell. It is written as |?:
It takes the below form (<falsePart> is optional);
<condition> |?: <truePart> [<falsePart>]
The <condition>, <truePart>, <falsePart> sections, can be normal expressions or [Script Blocks].
This operator also supported in Powershell Pipelines as well.
The implementation is provided in GitHub Here. |
Clear Import-Module -Name "VA.Script.Utility" -Force #Usage condition |?: truepart [falsePart] $true |?: "Print True" "Print False" #Usage {condition} |?: {trueBlock} [{falseBlock}]
{ $true } |?: { "Print True" } { "Print False" }
#You could provide condition directly without script block 1 -eq 2 |?: { "1 Equals 2" } { "1 Not Equals 2" } #You could omit False Part of the ternary { 1 -eq 2 } |?: { "1 Equals 2" }
#Use Ternary in Pipe line. Below will Print 3 (@( {$true}, $true, { $false }, $true) | ?: "YES" ).Length
No comments:
Post a Comment