none
DateTime Math

    Question

  • I am working on a script that checks if a backup is running and takes steps to fix it if needed.  The backup is verified by checking the timestamp on three files.  I want the script to pull those timestamps and compare them to the actual time.  I am pulling the timestamp of the files using 

    (Get-Item <filename>).LastWriteTime.DateTime

    and store it to a variable.  I store the Get-Date cmdlet result as another variable.

    I would like to compare these two variables and find out if the time difference exceeds 5 minutes.  I cannot find any clear guidelines on how to accomplish this.  Any help would be appreciated.

    Monday, March 20, 2017 5:56 PM

Answers

  • You need to use the AddMinutes() method such as the following

    (Get-Item <filename>).LastWriteTime.DateTime -gt (Get-Date).AddMinutes(-5)

    And if you want to to do something

    If ((Get-Item <filename>).LastWriteTime.DateTime -gt (Get-Date).AddMinutes(-5))

    {

    Do-Something

    }


    • Edited by Adam Devino Monday, March 20, 2017 6:12 PM
    • Proposed as answer by Adam Devino Monday, March 20, 2017 6:13 PM
    • Marked as answer by Ari W. _ Tuesday, March 21, 2017 12:36 PM
    Monday, March 20, 2017 6:12 PM

All replies

  • They are DateTime objects. You can subtract them and get a TimeSpan object, which has a Minutes property. Example:


    PS C:\> (([DateTime] "3:50pm") - ([DateTime] "3:44pm")).Minutes -gt 5
    True
    


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by jrv Monday, March 20, 2017 6:58 PM
    • Unproposed as answer by Ari W. _ Tuesday, March 21, 2017 12:37 PM
    Monday, March 20, 2017 6:06 PM
    Moderator
  • You need to use the AddMinutes() method such as the following

    (Get-Item <filename>).LastWriteTime.DateTime -gt (Get-Date).AddMinutes(-5)

    And if you want to to do something

    If ((Get-Item <filename>).LastWriteTime.DateTime -gt (Get-Date).AddMinutes(-5))

    {

    Do-Something

    }


    • Edited by Adam Devino Monday, March 20, 2017 6:12 PM
    • Proposed as answer by Adam Devino Monday, March 20, 2017 6:13 PM
    • Marked as answer by Ari W. _ Tuesday, March 21, 2017 12:36 PM
    Monday, March 20, 2017 6:12 PM