PowerShell: Check if File Has Been Modified in last 24 Hours


You can use the following basic syntax in PowerShell to check if a file has been modified in the last 24 hours:

if ((Get-Date) - (ls c:\users\bobbi\nba_data.xlsx).LastWriteTime).Days -lt 1)
{
echo "File modified in last 24 hours"
}
else
{
echo "File not modified in last 24 hours"
}

This particular example checks if the file named nba_data.csv has been modified in the last 24 hours.

If it has been modified then File modified in last 24 hours will be returned.

If it has not been modified then File not modified in last 24 hours will be returned.

The following example shows how to use this syntax in practice.

Example: How to Check if File Has Been Modified in Past 24 Hours Using PowerShell

Suppose we have a file named nba_data.xlsx that we have not modified in several months.

Suppose that this file is saved in the following location:

  • c:\users\bobbi\nba_data.xlsx

We can use the following syntax to check if this file has been modified in the last 24 hours:

if ((Get-Date) - (ls c:\users\bobbi\nba_data.xlsx).LastWriteTime).Days -lt 1)
{
echo "File modified in last 24 hours"
}
else
{
echo "File not modified in last 24 hours"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if file modified in last 24 hours

PowerShell returns File not modified in last 24 hours since the file has indeed not been modified in the last 24 hours.

If we’d like, we can see when the file was last modified by using the following syntax:

(ls c:\users\bobbi\nba_data.xlsx).LastWriteTime

The following screenshot shows how to use this syntax in practice:

We can see that the file was last modified on October 23, 2023.

This tutorial is currently being written on February 26, 2024, which is why PowerShell tells us that the file has not been modified in the last 24 hours.

Note: We used the Get-Date cmdlet to get the current date and time.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if File is Empty
PowerShell: How to Check if File Contains Specific String
PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String

Leave a Reply