How to copy directories preserving timestamps in Windows

#!/usr/bin/perl -w
#
# Touch dirs in a copy of the dir-tree for the mtime to match the original.
# Copyright 2008 Alexander Stcheblikin.

use Cwd;
use Win32API::File::Time qw{:win};      # Optional, see SetFileTime below

# Set your paths here
$src = "D:/src";        # The original directory tree
$dst = "C:/dst";        # A copy which needs directories timestamps fix

sub ScanDirectory {
    my ($workdir) = shift; # Relative to "$src/"!
    my ($startdir) = &cwd; # keep track of where we began
    my $srcworkdir = "$src/$workdir";

    chdir($srcworkdir) or die "Unable to enter dir $srcworkdir: $!\n";

    my @names = ();
    if (opendir(DIR, ".")) {
        @names = readdir(DIR);
        closedir(DIR);
    }
    else {
         warn "Unable to open $workdir: $!\n";
         # a warning is enough:
         # don't let some minor permissions problems stop the whole gig.
    }

    foreach my $name (@names){
        next if ($name eq ".");
        next if ($name eq "..");

        if (-d $name){
            &ScanDirectory("$workdir/$name");
            next;
        }
    }
    my ($atime, $mtime) = (stat("."))[8..9];    # used in utime() call
    chdir($startdir) or die "Unable to change to dir $startdir:$!\n";
    # We've done with the $workdir, it's safe now to re-touch the
    # dst equivalent of it.
    #utime($atime, $mtime, "$dst/$workdir")
    #   or warn "Unable to re-touch $workdir: $!\n";

    # An alternative using Win32API::File::Time
    # What's it good for: set the "Time Created"
    # - not found in UNIX-style utime
    SetFileTime ("$dst/$workdir", GetFileTime("$srcworkdir"));
    # Note:
    # Comment "SetFileTime()" and uncomment "utime()" above
    # if you cannot (or don't want) to use Win32API::File::Time
}

chdir($src) or die "Unable to enter src dir $src: $!\n";
&ScanDirectory(".");

1 Star2 Stars3 Stars4 Stars5 Stars ← Rate!


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>