Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare two dates in PowerShell & get difference in minutes

I need to compare LastWriteTime of a file and compare it to the current time. if the difference is greater then 45 minutes then I need to get a email alert.

Here is what I got so far.

$StartDate=(GET-DATE)

$EndDate=[datetime]”01/01/2014 00:00”

NEW-TIMESPAN –Start $StartDate –End $EndDate

In code above I need to replace $EndDate with Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime

I need to compare the LastWriteTime of file.html with current time.

Please help me store Get-Item C:\Users\myusername\Desktop\file.html | select LastWriteTime into $EndDate

so I can do the compare.

like image 989
user206168 Avatar asked Feb 19 '14 14:02

user206168


People also ask

How do I compare two date dates?

Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates.

How do you compare two dates in a type script?

Call the getTime() method on each date to get a timestamp. Compare the timestamp of the dates. If a date's timestamp is greater than another's, then that date comes after.


1 Answers

I think this should work:

if (((Get-Date) - (Get-ChildItem file.html).LastWriteTime).TotalMinutes -gt 45) {
 Write-Host "Old file"
}

Just to get the date into a variable would be:

$EndDate = (Get-Item C:\Users\myusername\Desktop\file.html).LastWriteTime

or

$EndDate = Get-Item C:\Users\myusername\Desktop\file.html |
    select -expandproperty LastWriteTime

The select -expandproperty syntax is needed on old versions of Powershell (prior to 3.0) when you might be accessing a property on multiple objects. I don't think it is needed even on Powershell 2 if there is only a single object.

like image 184
Duncan Avatar answered Oct 21 '22 04:10

Duncan