PowerShell: How to Compare LastWriteTime of File


You can use the following syntax in PowerShell to get the LastWriteTime property of a specific file:

$file_dt = (Get-Item players.txt).LastWriteTime

This particular example returns the LastWriteTime property of the file named players.txt in our current directory and saves it in a variable named $file_dt.

Once you’ve obtained this value, you can then compare it to another datetime in PowerShell.

The following example shows how to do so in practice.

Example: How to Compare LastWriteTime of File in PowerShell

We can use the following syntax to get the LastWriteTime property of the file named players.txt in our current directory:

$file_dt = (Get-Item players.txt).LastWriteTime

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

PowerShell compare LastWriteTime of file

We can see that this file has the following LastWriteTime value:

  • Wednesday, June 5, 2024 8:05:22 AM

We can then use the Get-Date cmdlet to obtain the current date and time when this article is being written:

$current_dt = Get-Date

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

This returns the following date and time:

  • Saturday, June 22, 2024 3:48:10 PM

We could use the -lt operator to check if the LastWriteTime property of our file is “less than” (i.e. earlier than) the current date and time:

$file_dt -lt $current_dt

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

PowerShell compare LastWriteTime to current date and time

This returns True since the LastWriteTime property of our file is indeed earlier than the current date and time.

We could also use the following syntax to find the difference between the LastWriteTime and the current date and time:

$current_dt - $file_dt

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

PowerShell difference between LastWriteTime and current time

From the output we can see that there is a difference of 17 days, 7 hours, 42 minutes and 47 seconds between the LastWriteTime of the file and the current date and time.

Note: You can find the complete documentation for the Get-Date cmdlet in PowerShell here.

Related Tutorials

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

How to Use Get-Date and Display Timezone in PowerShell
How to Compare Dates in PowerShell
How to Format a DateTime in PowerShell
How to Calculate Date Difference in PowerShell

Leave a Reply