powershellsyntaxoperatorsequality-operator

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


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"
$dateOfToday = '{0:yyyy-MM-dd}' -f (Get-Date)

$TimeDifference = [DateTime]$dateOfToday - [DateTime]$dateOfLicense 
if (($TimeDifference) = 14)
{
    Write-Host "test"
}

Even the difference between both days is 39, my code jumps in the if-clause and sends "test" to screen.

What am I doing wrong here?


Solution

  • 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"
    }