Compare date - How to check if a file was modified today

Welcome Forums General PowerShell Q&A Compare date - How to check if a file was modified today

Viewing 4 reply threads
  • Author
    Posts
    • #47787
      Participant
      Topics: 51
      Replies: 122
      Points: 78
      Rank: Member

      Hi,

      I'm creating a script to generate one HTML file with Dell EqualLogic data on it.
      In the end of the script I want to verify if the file was really modified.
      What I'm trying:

      * check today date
      * check file last write time
      * compare them

      Tested with this:

      $Today = Get-Date
      $FileDate = (Get-ChildItem ConfigEQL.html).LastWriteTime
      if ($FileDate -ge $Today){"ok"} else {"not ok"}
      

      and:

      $FileDate.CompareTo($Today)
      

      What is the best way (and working way) to do it?

    • #47793
      Participant
      Topics: 51
      Replies: 122
      Points: 78
      Rank: Member

      I was able to do it using this:

      $Xminutes = "2"
      $File = Get-ChildItem C:\PowerShell\Storage\Files\ConfigEQL.html | ? {$_.LastWriteTime -gt (Get-Date).AddMinutes(-$Xminutes)}
      

      Thanks!

    • #47849
      Participant
      Topics: 0
      Replies: 2
      Points: 0
      Rank: Member

      Hi,

      This is how I would do it:

      $Date = Get-Date;
      
      # ...run rest of the script...
      
      $Modified = $($(ls 'C:\PowerShell\Storage\Files\ConfigEQL.html').LastWriteTime -gt $Date);
      
      

      $Modified will be $true if it was modified, $false otherwise.

      What you posted last is putting the file in $File if it was modified in the last 2 minutes,
      otherwise it will be $null. It serves the purpose for you, I just prefer having the result in a
      boolean fashion, maybe for a later use.

      • #47939
        Participant
        Topics: 51
        Replies: 122
        Points: 78
        Rank: Member

        Balázs Ludányi,

        Thanks a lot! This is a much better way =]

    • #48101
      Participant
      Topics: 18
      Replies: 573
      Points: 32
      Rank: Member

      Put it all in one line rather than setting date at the beginning. All the extra formatting is unnecessary.

      (gci C:\PowerShell\Storage\Files\ConfigEQL.html).lastwritetime -gt [datetime]::today

      Alternatively use get-date and add minutes. (get-date).addminutes(-2)

    • #48107
      Participant
      Topics: 18
      Replies: 573
      Points: 32
      Rank: Member

      Powershell is really good at math as well.

      ([datetime]::now – (gci .\ConfigEQL.html).lastwritetime).totalminutes -lt 2

Viewing 4 reply threads
  • The topic ‘Compare date - How to check if a file was modified today’ is closed to new replies.