# POWERSHELL + UNC PATH + CREDENTIALS

Today I was faced with the fact that one of our backup processes needed to copy compressed database backups to a remote server over an UNC path every night. Of course were the UNC path protected with credentials other than the credentials my script were running under. The backup process is in fact a PowerShell script that is scheduled by the built in Windows scheduler. This may not seem as such a hard task and the solution is pretty simple but it took me a while to figure it out. If you’re thinking about mapping a network drive against the UNC path in advanced (I did too)… well then you can’t run your script with Windows built in scheduler because the context the Windows scheduler is running in can’t somehow find network drives that has been mapped in advanced… Also if you’re thinking about remapping the network drive in the script every time the script is executed something like:

$net = New-Object -comobject Wscript.Network$net.MapNetworkDrive("Q:","\\path\to\share",0,"domain\user","password")


well, then I think you’ll get a headache :) So after a while I started to think about how I would copy my files manually to the UNC path. If so; then I would just try to access the UNC path, Windows would ask me about credentials, I would enter them and then windows would cache the credentials I just entered while I do my copying! Ahaa! Maybe my script can do the same thing like this:

$uncServer = "\\10.11.12.124"$uncFullPath = "$uncServer\my\backup\folder"$username = "anton"
$password = "p@ssw0rd" net use$uncServer $password /USER:$username
try
{
#copy the backup
Copy-Item $zipFileName$uncFullPath
#remove all zips older than 1 month from the unc path
Get-ChildItem "$uncFullPath\*.zip" |? {$_.lastwritetime -le (Get-Date).AddMonths(-1)} |% {Remove-Item $_ -force } } catch [System.Exception] { WriteToLog -msg "could not copy backup to remote server...$_.Exception.Message" -type Error
}
finally {
net use \$uncServer /delete
}


And as it seems Windows does cache the credentials in this case too! :) Now backups are being copied to the remote server!