Calculating file date-time difference RRS feed

  • Question

  • In the PS command window I tested this and it worked as desired:


    PS E:\ADM_STAGE> $xx = Get-ChildItem("file1.txt")
    PS E:\ADM_STAGE> $zz = Get-ChildItem("file2.txt")

    PS E:\ADM_STAGE> echo $xx.lastWriteTime
    Wednesday, August 24, 2016 14:22:36

    PS E:\ADM_STAGE> echo $zz.lastWriteTime
    Monday, August 22, 2016 16:17:16

    PS E:\ADM_STAGE> $yy = $xx.LastWriteTime - $zz.LastWriteTime
    PS E:\ADM_STAGE> echo $yy

    Days              : 1
    TotalSeconds      : 165920.1615519
    TotalMilliseconds : 165920161.5519

    PS E:\ADM_STAGE> echo $yy.TotalMilliseconds


    When I use the same process in a script the code:

    $yy = $xx.LastWriteTime - $zz.LastWriteTime

    gives a "NULL" result

    What am I doing wrong? Anytime I tried something on the command-line it worked in a script (until now)

    Any suggestion would be greatly appreciated!

    • Moved by Bill_Stewart Tuesday, October 11, 2016 6:44 PM User answered own question
    Wednesday, August 24, 2016 10:40 PM

All replies

  • Don't use parenthesis with a CmdLet:

    $xx = Get-ChildItem  file1.txt

    It is not possible to understand your issue.

    Place this in the script editor window and execute it.

    if($f1 = Get-Item  file1.txt){
    	if($f2 = Get-Item  file2.txt){
    		$f1.LastWriteTime - $f2.LastWriteTime
    		Write-Host 'File 2 not found'
    	Write-Host 'File 1 not found'


    • Edited by jrv Wednesday, August 24, 2016 11:02 PM
    Wednesday, August 24, 2016 11:01 PM
  • In the famous words of Emily Litella "Never Mind"

     I couldn't see the forest for the trees, i.e. I did a step getting LastWriteTime into a variable "A", and the doing the math again using the member LastWriteTime  on variable "A" again (DUH!)

    $A = $xx'LastWriteTime 

    $B = $zz.LastWriteTime 

    $diff = $A.LastWriteTime  - $B.LastWriteTime  (!)

    Of course this doesn't work since $A & $B are not of type FileInfo

    THX for your help, made me look more closely at my code.

    Thursday, August 25, 2016 12:14 AM
  • No excuse for "Never Mind".  Just "byte" the bullet and move on.


    Thursday, August 25, 2016 12:51 AM