Copying folder hierarchy with date filter and elimination of empty folders

Ever need to copy a tree of folders? I had to do this only for files older than a specified date. Plus empty folders were not welcomed. How to go about this?

We’ll approach this in four easy steps. First we’ll set the source, destination and threshold date, followed by recreating the empty folder structure on the target:

$sourceLocation = "\\ny-srv-fs3\Reserve"
$DestLocation = "D:\plautj\ACT\TMP"
$thresh = get-date "December 31, 2006"
xcopy $sourceLocation $DestLocation /T

Next we’ll get the full set of files and folders:

$q = Get-ChildItem $sourceLocation  -Recurse

We will now copy all the files older than the threshold:

foreach ($qItem in $q)
    if (!$qitem.PSiscontainer)
        if ($qItem.LastWriteTime -lt $thresh)
            $DestItemLoc = $qitem.FullName.replace($sourceLocation,$DestLocation)
            copy-item $qitem.FullName  $DestItemLoc

Lastly, let’s delete empty folders. The kep is specifying the AllDirectories search option, otherwise it will delete folders that are devoid of immediate files, but which have files in subfolders:

    $a = Get-ChildItem $DestLocation -recurse | Where-Object {$_.PSIsContainer -eq $True}
    $a | Where-Object {$_.getfiles("*",[System.IO.SearchOption]::AllDirectories).Count -lt 1} | Select-Object FullName | ForEach-Object {remove-item $_.fullname -recurse}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s