Carbon
Carbon

Reputation: 3943

Why do two sleep statements chained in powershell fail?

In Win command line, you can do cmd1 && cmd2 and cmd2 will only be executed if cmd1 succeeded. I think the powershell equivalent, based on other answers here, would be (cmd1) -and (cmd2). However, I'm seeing weird behavior when testing it - specifically, I'm getting a fail when I should be getting true. Here's a minimal replicating example.

PS>(Start-Sleep 1)
PS>$?
True
PS>(Start-Sleep 1) -and (Start-Sleep 1)
False
PS>$?
True
PS>$z = (Start-Sleep 1) -and (Start-Sleep 1)
False
PS>$z
False
PS>$?
True

Why are the sleeps failing to chain, and why is $z not matching $??

Upvotes: 2

Views: 155

Answers (2)

js2010
js2010

Reputation: 27516

Start-Sleep is $null. But $null -and $null is $false.

PS C:\users\js> $a = Start-Sleep 1
PS C:\users\js> $a
PS C:\users\js> $a -eq $null
True
PS C:\users\js> $a -and $a
False
PS C:\users\js> [bool]$a
False
PS C:\users\js> $false -and $false
False

Short circuiting.

PS C:\users\js> $true -and (write-host hi)
hi
False
PS C:\users\js> $false -and (write-host hi)
False
PS C:\users\js> $true -or (write-host hi)
True
PS C:\users\js> $false -or (write-host hi)
hi
False

Note that in PS, -and and -or have the same precedence!

Upvotes: 1

ncfx1099
ncfx1099

Reputation: 367

These commands are not doing what you think they're doing. Rather than executing two commands, you are asking your interpreter to evaluate two statements based on the output of the commands you have in parenthesis.

In Powershell, parenthesis are used to denote a statement that is executed first. Start-Sleep will return $NULL upon return because nothing was written to the buffer during execution or on return. Powershell evaluates $NULL as false, so when it comes to the -and check, -and cheats and sees that the input is $false, probably to save time.

(Start-Sleep -S 1) == $false

So what you're actually doing is saying:

$null -and $null

Which is, of course, $false. Because $false when AND'ed with $false is $false.

Upvotes: 4

Related Questions