Copy Files via a Mapped Drive using Powershell

Here’s a quick script to copy files via a mapped drive in powershell.  In my case, this was copying a bunch of .bak files located in separate directories located in the $path.  It only copies the latest .bak file. 

I should also warn you, this is kind of hard to test.  I believe there is a bug in the that will error out (I forget the text of the error, but you’ll see it soon enough) that will keep erroring when you run it additional times. 

When this is run as a job, say a couple times daily it seems to work fine, but this makes debugging & stepping through the code a frustrating endeavor.  I don’t know if Powershell 3 has an easier way to do this.  I may have to investigate.

As always, use at your own risk.  Worked for me, may not for you.

$path = "c:\SourceDirectory\"
$destPath = "\\\TargetDirectory"
$destDrive = "x:"

function CopyLastBackup
    $net = new-object -ComObject WScript.Network
        $net.MapNetworkDrive($destDrive, $destPath, $false, "UserName", "Password")
        $dirs = Get-ChildItem $path | where {$_.PSIsContainer} | where {$_.GetFiles().Count -ne 0}
        foreach($dir in $dirs)
            #write-host $dir.FullName
			$file = Get-ChildItem -LiteralPath $dir.FullName -include "*.bak" | sort CreationTime -Descending | select -First 1
        	Copy-Item -LiteralPath $file.FullName -Destination $destDrive -force
        return 0;
        write-host $error[0]
        return 1
        #return ("Error: {0}" -f $error[0])

$ret = CopyLastBackup
if($ret -eq 1)
    throw "Failure"

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 )

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.