16

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?

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
  • 4
    You didn't read past that, did you ;) Later in the document you refer to: "The Windows PowerShell logical operators evaluate only the statements required to determine the truth value of the statement..." – Andrew Morton Nov 05 '14 at 20:39
  • 1
    @AndrewMorton - I did actually, but I was confused by the description of the `-or` operator. [Keith Hill's answer](http://stackoverflow.com/a/26768902/682480) shows that it does short-circuit by default and helped clear things up for me. – Code Maverick Nov 06 '14 at 01:12
  • 2
    logically (ahem, pun acknowledged), `-xor` could not possibly short circuit... right? It must evaluate both sides of the expression to determine the exclusivity... ... right? – Code Jockey Aug 17 '15 at 19:39
  • @CodeJockey sounds right. – Ohad Schneider Mar 22 '16 at 19:28

2 Answers2

28

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • 2
    Very interesting. I was wondering if `-or` did that by default, but the documentation stated otherwise. But now, after re-reading the description, it does say `when either or both`, so I guess that would mean that it does some form of short-circuiting by default. – Code Maverick Nov 05 '14 at 23:42
  • 2
    Yes it does short-circuiting by default for the -and & -or operators. – Keith Hill Nov 06 '14 at 01:04
  • 1
    [But it is not the short circuiting that has been around in *nix shells for decades.](https://stackoverflow.com/a/41816341/711422) – rjt May 27 '17 at 19:08
1

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/

Radityo Ardi
  • 138
  • 6