Last file in folder, wrong output

This topic contains 4 replies, has 4 voices, and was last updated by Profile photo of Maarten Vekens Maarten Vekens 1 year, 2 months ago.

  • Author
  • #28225
    Profile photo of Maarten Vekens
    Maarten Vekens

    When I perform this command on the command line, I receive the correct response

    $Outputfiles = Get-ChildItem 'D:\TST\log\input' -Recurse | where-object LastWriteTime | select -First 1

    When I do this in a script I always receive the same result, even there are new files.

    Any idea?

  • #28226
    Profile photo of Richard Siddaway
    Richard Siddaway

    I'm a little puzzled why you're using where-object. I'd have thought if you wanted the last file in the folder you would sort on LastWriteTime rather than just test it exists

  • #28227
    Profile photo of Wilfredo Perez
    Wilfredo Perez

    Can we see the code – please

  • #28230
    Profile photo of Matt McNabb
    Matt McNabb

    It seems the OP has assumed that the LastWriteTime property means "this is the last file that was written to in the folder." If you just want the most recently written file, use Sort-Object instead of Where-Object:

    Get-ChildItem 'D:\TST\log\input' -Recurse -File |
        sort lastwritetime -Descending |
        select -First 1
  • #28261
    Profile photo of Maarten Vekens
    Maarten Vekens

    thank you! the problem was caused due to the fact that after I moved the file from another location the modify time was not changed.

You must be logged in to reply to this topic.