user829174
user829174

Reputation: 6362

PowerShell Read file Modified Date and check if it was modified in the last X hours

Using Powershell, How can I read a modified date of a certain file and check it it was modified in the last 24 hours?

This is was I got so far:

$temp = Get-Item D:\somefile.txt | select LastWriteTime

EDIT Also, I need an example of how to show it was changed in the last 5 seconds

Upvotes: 3

Views: 28346

Answers (3)

Loïc MICHEL
Loïc MICHEL

Reputation: 26150

a one liner :

if ( ((Get-Date) - (ls d:\somefile).LastWriteTime).Day -lt 1) {Write-Output "recently modified"}

to you second question :

$diff=((ls d:\somefile).LastWriteTime - (Get-Date)).TotalSeconds
 if ($diff -gt -5) {Write-Output "recent"}

Upvotes: 6

Sibeesh Venu
Sibeesh Venu

Reputation: 21739

I had gone through a similar requirement recently, where I wanted to check the existence of an XML file and to check whether it is modified in the last one hour. Here is the script to do that.

$files = Get-ChildItem C:\XmlFolder -Filter *.xml
$timeNow = Get-Date -Format HH
foreach($file in $files)
{
    if ( $file.LastWriteTime.ToString('HH') -eq $timeNow)
    {
        $file.Name
    }
}

Now run the command.

enter image description here

Upvotes: 2

hysh_00
hysh_00

Reputation: 839

In Kayasax's answer, Days should be Day.

if ( ((get-date) - (ls d:\somefile).LastWriteTime).day -lt 1){echo "recently modified"}

Upvotes: 1

Related Questions