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 wscript.network 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 = "\\192.168.1.1\TargetDirectory"
$destDrive = "x:"

function CopyLastBackup
{
    $net = new-object -ComObject WScript.Network
    try
    {
        $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
        }
        $net.RemoveNetworkDrive($destDrive,"true","true")
        return 0;
    }
    catch
    {
        write-host $error[0]
        return 1
        #return ("Error: {0}" -f $error[0])
    }
    finally
    {
        $net.RemoveNetworkDrive($destDrive,"true","true")
    }
    
}

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: