Master Station Log
techno-rants, musings, misc geek writing, and occasional caffeine binges
PowerShell: UNC File Copy with Credentials
Date: 2019-05-04 09:58:53
Copy a file with PowerShell to a remote share with a hard coded user and password. Sounds simple, but sometimes, things just aren't easy... The trouble I had with this task was adding the Credentials (different than the context the PowerShell was running under) and then mapping a PSDrive for the Credentials to apply to. But, if the PSDrive is already there, you'll get an error. So you have to check for the PSDrive first and drop it, argghh...
$uncLoginUser = "jason"
$uncLoginPass = "YourPassword" | ConvertTo-SecureString -asPlainText -Force
$uncServer = "MtnBird"
$uncShare = "Backups"
$uncFullPath = "\\" + $uncServer + "\" + $uncShare
$localFile = "C:\Temp\ImportMe.csv"
$credential = New-Object System.Management.Automation.PSCredential($uncLoginUser,$uncLoginPass)
Get-PSDrive $global:uncServer -EA SilentlyContinue | Remove-PSDrive -Force
New-PSDrive -Name $uncServer -PSProvider "FileSystem" -Root $uncFullPath -Credential $credential | Out-Null
$psDrive = $uncServer + ":\"
Copy-Item -Path $localFile -Destination $psDrive -Force -EA Stop