Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform short-circuit evaluation in Windows PowerShell 4.0?

Technet's about_Logical_Operators with respect to Windows PowerShell 4.0 states the following:

Operator     Description                        Example

--------     ------------------------------     ------------------------
-or          Logical or. TRUE when either       (1 -eq 1) -or (1 -eq 2) 
             or both statements are TRUE.       True

-xor         Logical exclusive or. TRUE         (1 -eq 1) -xor (2 -eq 2)
             only when one of the statements    False 
             is TRUE and the other is FALSE.

Neither seem to perform short-circuit evaluation.

How can I mimic the C# || or VB OrElse in Windows Powershell 4.0?

like image 206
Code Maverick Avatar asked Nov 05 '14 20:11

Code Maverick


2 Answers

A simple set of test cases show that short-circuiting works:

PS C:\> 1 -eq 0 -or $(Write-Host 'foo')
foo
False
PS C:\> 1 -eq 1 -or $(Write-Host 'foo')
True

PS C:\> 1 -eq 1 -and $(Write-Host 'foo')
foo
False
PS C:\> 1 -eq 0 -and $(Write-Host 'foo')
False
like image 195
Keith Hill Avatar answered Nov 12 '22 23:11

Keith Hill


I was looking for the same, came across this answer. The best so far in my opinion...

$cueNumber = 512
@{ $true = "This is true"; $false = "This is false" }[$cueNumber -gt 500]

Reference: https://adamtheautomator.com/a-simpler-ifthen-conditional-logic-in-powershell/

like image 29
Radityo Ardi Avatar answered Nov 12 '22 23:11

Radityo Ardi