Reputation: 4370
Running the following command in Powershell 7.0.3 returns true
[datetime]'2020-08-09' -eq 'August 9, 2020'
But, I want to replace the right side of the command with Get-Date
. I wonder how I can do it. If I'm not wrong (Please correct me if I am), we can do it in bash using the by enclosing the command in ticks(`).
I've tried the Invoke-Command cmdlet but I get the same error:
> [datetime]'2020-08-09' -eq Invoke-Command Get-Date
ParserError:
Line |
1 | [datetime]'2020-08-09' -eq Invoke-Command Get-Date
| ~
| You must provide a value expression following the '-eq' operator.
Can someone help me out with it or point me in the right direction?
Upvotes: 0
Views: 107
Reputation: 61068
To compare a datetime object with another, you need to make sure that other part is also a datetime object. This is why you need to put brackets around the right-hand side of the equasion, so the command in there is evaluated first.
As Lee_Dailey mentioned, the result of [datetime]'2020-08-09'
is a date object with the time part set to 0:00:00 (midnight).
As example of how it will work is:
[datetime]'2020-08-09' -eq (Get-Date).Date
Another thing to consider is the fact that constructing the date using [datetime]'2020-08-09'
will leave you with a datetime object that has its .Kind
property set to Unspecified
.
If you are comparing this to the resulting datetime object that stores a UTC date (= has its .Kind
property set to 'Utc)', the equasion will still go wrong (unless your current timezone IS actually UTC)
We can fake this by doing
[datetime]'2020-08-09' -eq (Get-Date).Date.ToUniversalTime()
Which in my timezone would return False.
P.S. It is wrong to compare a datetime object to a formatted date string.
It may have worked in your case, because apparently the .ToString()
method of a datetime object happens to format in 'yyyy-MM-dd' on your system. On different locales however comparing like this will fail .
Upvotes: 1