Copying folder hierarchy with date filter and elimination of empty folders

31

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-fs3Reserve"
$DestLocation = "D:plautjACTTMP"
$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}

Share this entry

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents

Categories

Categories