PowerShell Compare LastWriteTime of Two Files

PowerShell compare lastwritetime of two files

Using LastWriteTime property

To compare LastWriteTime of two files in PowerShell:

  • Use Get-Item to get items.
  • Use the if-else block to compare LastWriteTime of both files.

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 the LastWriteTime of two files in PowerShell.
  • Use the if-else block to determine if the LastWriteTime of both files is the same.

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.

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 a TimeSpan object in PowerShell.
  • Use the if-else block to determine if the LastWriteTime of both files is the same or different.

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 the TimeSpan object denoting the time interval of 0.

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’s lastwritetime property.
    • Use if-else blocks with -gt and -lt comparison operators to compare the LastWriteTime.
    • Use the Write-Output cmdlet to print if the first file’s last write time is same, older, or newer than the current file.

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.

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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *