Thursday, September 20, 2007

Create dummy directory tree

 

The "New-DummyTree" function creates a directory tree duplicate. The new directory tree will be an exact copy of the source directory, including file names and there's date attributes, only files will be 0 bytes long. Then you can test your scripting scenarios on its structure.

I used it only once when I tested a mass file processing activity (copy, delete, rename, archive (with New-RarArchive) and so on.

I couldn't test it against the real directory tree since it was based on the files date attributes, not to mention that the source files were very big in size, and I wanted to test the script as one piece and not just part of it in separate files.

It also demonstrates how you can alter a file or directory date attributes, such as LastWriteTime, etc.

So, for what it's worth...


function New-DummyTree{
   
   param(
        [string]$source=$(throw "Invalid source directory path"),
        [string]$destination
    )

    if( -not (Test-Path $source -pathType container)){
        write-error "Invalid source directory path: <$source>";
        break;
    }

    
    get-childitem $source -recurse | where {-not $_.psiscontainer} | foreach {
        $path="{0}{1}" -f $destination,$($_.directoryname.remove(0,$source.length));
        $file=new-item -path $path -name $_.name -type file -force;
        $file.CreationTime=$_.CreationTime;
        $file.LastWriteTime=$_.LastWriteTime;
        $file.LastAccessTime=$_.LastAccessTime;
    }

    #set-location $destination
}

 

Note, You don't need to create the destination directory, It will be created on the fly if it doesn't exist.

Usage:

New-DummyTree <SourcePath> <DestinationPath>

No comments: