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

前端 未结 3 1957
天命终不由人
天命终不由人 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:33

    You are assigning 14 to $TimeDifference. Instead you wan't to compare the Days property using -le:

    if ($TimeDifference.Days -le 14)
    {
        Write-Host "test"
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 03:59

    Not better solution of Martin, just an shorty code

    $dateOfLicense = [DateTime]"2017-04-20"
    $TimeDifferenceDays = ((Get-Date) - $dateOfLicense).Days 
    
    if ($TimeDifferenceDays -lt 14)
    {
        Write-Host "test"
    }
    
    0 讨论(0)
提交回复
热议问题