DateTime subtraction not working in PowerShell - assignment vs. equality operator

前端 未结 3 1962
天命终不由人
天命终不由人 2020-12-04 03:00

Today (2017-05-29) I am using PowerShell 5.0.10586.117 on Windows 7 Enterprise and run the following (shortened):

$dateOfLicense = \"2017-04-20\"
$dateOfToda         


        
3条回答
  •  清歌不尽
    2020-12-04 03:48

    To complement Martin Brandl's helpful answer:

    Like many other languages - but unlike VBScript, for instance - PowerShell uses distinct symbols for:

    • the assignment operator (=)
    • vs. the equality operator (-eq).

    This distinction enables using assignments as expressions, which is what you inadvertently did:

    if (($TimeDifference) = 14) ... # same as: if ($TimeDifference = 14) ...
    

    assigns 14 to variable $TimeDifference, as Martin explains, and, because the assignment is (of necessity, to serve as a conditional for if) enclosed in (...), returns the assigned value (the inner (...) around $TimeDifference make no difference here, however).

    Therefore the (...) expression evaluated by if has value 14 - a nonzero number - it is interpreted as $true in this Boolean context.

    To learn more about PowerShell's operators, run Get-Help about_Operators; to learn about how PowerShell interprets arbitrary values as Booleans in conditionals, see the bottom section of this answer.


    Finally, here's a streamlined version of your code that doesn't require intermediate variables, uses a cast to convert the string to a [datetime] instance and uses [datetime]::now, the more efficient equivalent of Get-Date (though that will rarely matter).

    if (([datetime]::now - [datetime] '2017-04-20').Days -eq 14) {
      "test"
    }
    

    Note how "test" as a statement by itself implicitly sends output to PowerShell's (success) output stream, which prints to the console by default.
    Write-Host bypasses this stream and should generally be avoided.

提交回复
热议问题