windows - Powershell LastWriteTime is incorrect

07
2014-07
  • nate

    I am running the following script to create directories based on the first 9 characters in the filenames in the directory and then moving te files into these directories based on their filenames.

    dir | %{ 
        $id = $_.Name.SubString(0,9); 
        if(-not (Test-Path $id)) {mkdir $id}; 
        mv $_ "$id\$_";}
    

    Now, what I have found is that after running the script the folders are being marked with a LastWriteTime several years in the past.

    Here is the output from Powershell

    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    d----        13/04/2006   7:25 PM            XXX095_00
    d----        13/04/2006   7:29 PM            XXX285_0_
    

    Can anyone tell me where this LastWriteTime is coming from?

  • Answers
  • dangph

    Moving a file doesn't appear to count as a write. I guess that's because you aren't actually writing to the contents of the file. But you can update the LastWriteTime yourself. Try this:

    dir | %{ 
        $id = $_.Name.SubString(0,9); 
        if(-not (Test-Path $id)) {mkdir $id};
        $_.LastWriteTime = Get-Date;           # <---- Added line.
        mv $_ "$id\$_";}
    

    (You don't need the semicolons, by the way, when your statements are on separate lines.)


  • Related Question

    Is PowerShell part of Windows 2008 Server?
  • David.Chu.ca

    Not sure if Powershell is a part of Window 2008 Server? I cannot find it from cmd console. Just to avoid to download it again.


  • Related Answers
  • John T

    It is indeed bundled with Server 2008, although it needs to be installed using the method you mentioned. Note that this is version 1.0 of PowerShell, 2.0 is now available here (see bottom of page).

  • David.Chu.ca

    I think I find out the solution. From Server Manager->Features, there is one for "Windows PowerShell". It is unchecked by default.