Search code examples
powershellget-childitem

Get-child item Lastwritetime is not returning properly


I am trying to get the CreationTime and Lastwritetime using get-childitem command and comparing it with the same assembly time to check if there is any difference for every 5 minutes.

Strangely there is a difference in milliseconds for every time when I fetch the records if the assembly did not change and it is causing the compare-object to fail.

Is there any way to fix this, other than converting the time to string format?

below is the command to fetch the details of the Assemblies

Get-ChildItem -Path 'C:\Windows\Microsoft.NET\assembly\GAC_MSIL' -include *.dll -Recurse|select @{Label=”AssemblyName”;Expression={$_.Name}},@{Label=”Size”; Expression={$_.Length}},@{label="Version";expression={if($_.versioninfo.productversion -eq $null) { 
              "NULL"
            } else { 
              $_.versioninfo.productversion
            }
          }},@{Label=”CreationTime”; Expression={$_.CreationTime}},@{Label=”LastWriteTimeUtc”; Expression={$_.LastWriteTimeUtc}}

and running this command after 5 minutes and comparing with compare-object

compare-object -$oldobject $newObject -property Name,Lastwritetime

Solution

  • I do not know the exact reasons why there is a difference of some milliseconds (most probably an inaccurate floating point number).

    The usual solution for a problem like this is to use an epsilon value in your comparisons (pretty common in game programming among others).

    Set-Variable -name EPSILON -value ([double]0.00001) #-option Constant
    function Is-Same {
        Param(
        [Parameter(Mandatory = $true)] [double]$a,
        [Parameter(Mandatory = $true)] [double]$b
        )
        #return $a - $b;
        return [math]::abs($a - $b) -le $EPSILON;
    }
    
    Is-Same 1.000001 1.0000
    Is-Same 1.00001 1.0000
    Is-Same 1.0001 1.0000
    

    True
    False
    False

    Adjust the epsilon value as needed. (adhering numerical limits)