Table of Contents
Using LastWriteTime property
To compare LastWriteTime
of two files in PowerShell:
- Use
Get-Item
to get items. - Use the
if-else
block to compareLastWriteTime
of both files.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$fileName1 = Get-Item "E:\Test\file1.txt" $fileName2 = Get-Item "E:\Test\file2.txt" if ($fileName1.LastWriteTime -eq $fileName2.LastWriteTime) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is same." } elseif ($fileName1.LastWriteTime -gt $fileName2.LastWriteTime) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' is greater than '$($fileName2.Name)'" } else{ Write-Host "The LastWriteTime of the '$($fileName1.Name)' is greater lesser '$($fileName2.Name)'" } |
1 2 3 |
The LastWriteTime of the 'file1.txt' is greater than 'file2.txt' |
Using Compare-Object
Cmdlet
To compare the LastWriteTime
of two files in PowerShell:
- Use
Get-Item
to get items. - Use the
Compare-Object
cmdlet to compare theLastWriteTime
of two files in PowerShell. - Use the
if-else
block to determine if theLastWriteTime
of both files is the same.
1 2 3 4 5 6 7 8 9 10 |
$fileName1 = Get-Item "E:\Test\file1.txt" $fileName2 = Get-Item "E:\Test\file2.txt" $fileComparison = Compare-Object -ReferenceObject $fileName1.LastWriteTime -DifferenceObject $fileName2.LastWriteTime if ($fileComparison -eq $null) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is same." } else { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is different." } |
1 2 3 |
The LastWriteTime of the 'file1.txt' and 'file2.txt' is different. |
First, we used the Get-Item
cmdlet to get items at the given location and stored them in the $fileName1
and $fileName2
variables. This cmdlet is used to get items only from the specified location, not their content unless we use a wildcard character (*
) to request an item’s entire content. Note that PowerShell providers use this cmdlet to traverse through various kinds of data stores.
Then, we used the Compare-Object cmdlet to compare the LastWriteTime
of $fileName1
& $fileName2
, and saved it in $fileComparison
variable. This cmdlet is used to compare two sets of objects in PowerShell. Here, the first set of objects is the ReferenceObject, while the second set of objects is the DifferenceObject. In our case, $fileName1.LastWriteTime
is the reference
and $fileName2.LastWriteTime
is the Difference
.
The Compare-Object
look over the available methods that can be used to compare the entire object; if it cannot find any appropriate method, then ToString()
will be used to compare string results. While using this cmdlet, we can provide one or multiple properties that can be used to perform a comparison.
When properties are specified, the
Compare-Object
cmdlet only compares those properties’ values.
The outcome of the comparison represents if the specified property appeared in the DifferenceObject
(=>
) only or ReferenceObject
(<=
) only. On the other hand, if the IncludeEqual
is used, then the ==
operator denotes that the value is present in both objects.
Finally, we used the if-else
block to compare the $fileComparison
with $null
using the -eq
(equal to) operator. If the value of the $fileComparison
variable is equal to null, we used the Write-Host
cmdlet to print a message saying LastWriteTime
is the same; otherwise, different.
Remember, if the ReferenceObject
or the DifferenceObject
is null ($null
), then Compare-Object
will generate a terminating error saying it cannot bind the argument to parameter DifferenceObject
because it is null; see the following example to make your concept clear.
1 2 3 4 5 6 7 8 9 10 |
$fileName1 = Get-Item "E:\Test\file1.txt" $fileName2 = $null $fileComparison = Compare-Object -ReferenceObject $fileName1.LastWriteTime -DifferenceObject $fileName2.LastWriteTime if ($fileComparison -eq $null) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is same." } else { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is different." } |
1 2 3 |
Compare-Object: Cannot bind argument to parameter 'DifferenceObject' because it is null. |
We got the above error because $fileName2
is set to null ($null
).
Using the New-TimeSpan
Cmdlet
To compare the LastWriteTime
of two files in PowerShell:
- Use the
Get-Item
cmdlet to get items from the given locations. - Use the
New-TimeSpan
cmdlet to create aTimeSpan
object in PowerShell. - Use the
if-else
block to determine if theLastWriteTime
of both files is the same or different.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$fileName1 = Get-Item "E:\Test\file1.txt" $fileName2 = Get-Item "E:\Test\file2.txt" $lastWriteTimeDifference = New-TimeSpan $fileName1.LastWriteTime $fileName2.LastWriteTime if ($lastWriteTimeDifference.TotalSeconds -eq 0) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' and '$($fileName2.Name)' is the same." } elseif ($fileName1.LastWriteTime -gt 0) { Write-Host "The LastWriteTime of the '$($fileName1.Name)' is greater than '$($fileName2.Name)'" } else{ Write-Host "The LastWriteTime of the '$($fileName1.Name)' is greater lesser '$($fileName2.Name)'" } |
1 2 3 |
The LastWriteTime of the 'file1.txt' is greater than 'file2.txt' |
This code snippet is similar to the first example in the previous section, where we used the Compare-Object
cmdlet, except for two differences. First, we used the New-TimeSpan
cmdlet; the second was to have a different expression in the if
statement. The New-TimeSpan cmdlet is used to create a TimeSpan
object that we stored in $lastWriteTimeDifference
variable, representing a time interval that we can use to add or subtract time from the DateTime
objects.
If we do not use any parameters, the
New-TimeSpan
cmdlet will return theTimeSpan
object denoting the time interval of0
.
Here, we used the if
statement with the -eq
(equal to) operator to compare if the value of the TotalSeconds
property of the $lastWriteTimeDifference
object is equal to 0
. If so, the if
block will be executed; otherwise, elseif
block will check if the value of the TotalSeconds
property of the $lastWriteTimeDifference
object is greater to 0
; otherwise else will be executed.
Suppose we have n
number of files in a particular location that we want to compare the LastWriteTime
of one file with rest of the files. Then, we can use the following approach to fulfil the project needs.
Using Get-ItemProperty
Cmdlet
To compare the LastWriteTime
of two files in PowerShell:
- Use the
Get-ChildItem
cmdlet to get items/child items from the given location. - Use the Where-Object cmdlet to filter the objects received from the
Get-ChildItem
cmdlet. - Save the first file object and its
LastWriteTime
in two separate variables. - Use the
foreach
loop to iterate over all the filtered objects. - In each iteration:
- Use the
Get-ItemProperty
cmdlet to get a specified item’slastwritetime
property. - Use
if-else
blocks with-gt
and-lt
comparison operators to compare theLastWriteTime
. - Use the
Write-Output
cmdlet to print if the first file’s last write time is same, older, or newer than the current file.
- Use the
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$source = "E:\Test" $allFiles =Get-ChildItem $source | Where-Object { !$_.PSIsContainer } $firstFile = $allFiles[0] $firstFileLastWriteTime = [datetime](Get-ItemProperty -Path $firstFile.FullName -Name LastWriteTime).LastWriteTime foreach ($file in $allFiles) { $dateTime = [datetime](Get-ItemProperty -Path $file.FullName -Name LastWriteTime).lastwritetime if ($dateTime -gt $firstFileLastWriteTime) { Write-Output "$($file.Name) - Last Write Time is newer than $($firstFile.Name)" } elseif ($dateTime -lt $firstFileLastWriteTime) { Write-Output "$($file.Name) - Last Write Time is older than $($firstFile.Name)" } else { Write-Output "$($file.Name) - Last Write Time is the same as $($firstFile.Name)" } } |
1 2 3 4 5 6 7 8 9 10 11 |
computersList.txt - Last Write Time is the same as computersList.txt file - Copy.doc - Last Write Time is older than computersList.txt file - Copy.pdf - Last Write Time is newer than computersList.txt file.docx - Last Write Time is older than computersList.txt file.pdf - Last Write Time is newer than computersList.txt file2.txt - Last Write Time is older than computersList.txt file3.txt - Last Write Time is older than computersList.txt file4.txt - Last Write Time is older than computersList.txt testPS.ps1 - Last Write Time is newer than computersList.txt |
First, we defined and initialized a variable named $source
with the source location’s path, which is E:\Test in our case. Next, we used Get-ChildItem cmdlet to retrieve the items in the specified location(s), which is $source
in the above example. Remember, the Get-ChildItem
can get items and child-items from the given directory and subdirectories and returns them as System.IO.FileInfo
and System.IO.DirectoryInfo
objects.
As we are only interested in files and don’t want to dive into the directories or subdirectories, we used the Where-Object
cmdlet to filter and select those objects that are not the containers (directories). How? Let’s understand it. In the { !$_.PSIsContainer }
expression, the {}
represents the script block, the $_
represents the current object in the pipeline, and !
is used to negate the value of the PSIsContainer
property. It means the Where-Object
will filter all the containers and select only those objects that are not the containers. Then, we stored the resulting values in the $allFiles
variable.
After that, we retrieved the first file using $allFiles[0]
and stored it in $firstFile
variable. We also stored the LastWriteTime
of the $firstFile
in $firstFileLastWriteTime
variable.
Next, we used the foreach
loop to iterate over the $allFiles
. In every iteration, we used the Get-ItemProperty
cmdlet to get the properties of the current item; in the above code, we got the lastwritetime
property, cast its type to DATETIME
using [datetime]
and stored it in the $dateTime
variable. After that, we used if-else
blocks with -gt
and -lt
operators to compare the LastWriteTime
of the $firstFile
with the current item’s last write time and checked whether it is older, same, or newer than the first file’s last write time.
In each conditional block, we Write-Output
cmdlet to print the current item’s name (the file name) and described if the last write time is same, older, or newer than the computersList.txt
which was our first file . We can use the following solution if you want the Mode
, LastWriteTime
, Length
, and Name
of all the files in the specified location.
Using ls
Command
Use the ls
command to list the LastWriteTime
of multiple files in the specified location whose LastWriteTime
is greater than one day.
1 2 3 |
ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1} |
1 2 3 4 5 6 7 8 |
Directory: E:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/8/2023 9:26 PM 196 file1.txt -a---- 2/8/2023 9:31 PM 83 file2.txt -a---- 2/18/2023 12:18 PM 82 file3.txt |
We have already learned all the commands used in this example. You might see ls
as a new command, but that is an alias of the Get-ChildItem
cmdlet already explained in the previous section. The ls
retrieved all the files and subdirectories in the current directory that were forwarded to the Where-Object
cmdlet using pipeline (|
), where Where-Object
filtered them based on the LastWriteTime
property.
We have already learned that the New-TimeSpan
cmdlet creates a TimeSpan
object; here, its Days
property denotes the number of whole days in a time span. The expression preceded by the Where-Object
cmdlet determines whether the TimeSpan
object’s Days
property is greater than or equal to the 1
, which means the current item was last written more than one day ago. If this expression is True
, the current item will be added to the output.
If you are only interested in getting Day
, Date
, and Time
, we can use ls
as follows.
1 2 3 4 |
$source = "E:\Test" (ls $source).LastWriteTime |
1 2 3 4 5 |
Wednesday, February 8, 2023 9:26:59 PM Wednesday, February 8, 2023 9:31:21 PM Saturday, February 18, 2023 12:18:35 PM |
We can do different comparisons in all of the above examples based on our project needs such as
-gt
(greater than),lt
(less than),-ge
(greater than or equal to) or-le
(less than or equal to).
That’s all about powerShell compare LastWriteTime of two Files.