UNC path New-PSDrive script with -Credential not working

Hi techies

I’m new to PS script and need your urgent help.

My requirement is to copy the data files from my internal server to a remote third party file-share server on a daily basis.(site to site VPN is configured)

Please see the below script I used.

$Source = “\localserver\Y$\Test*”
$Dest = “\\TestData\”
$Username = “remotedomain\test.user”
$Password = ConvertTo-SecureString ‘password’ -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PsCredential ($Username,$Password)
New-PSDrive -Name ‘W’ -PSProvider FileSystem -Root $Dest -Credential $Credential -Persist
Copy-Item -Path $Source -Destination "W:" -Recurse -passthru
Remove-PSDrive W

The issue I’m facing is, If I add the third party credentials to Windows “Credential manager” and then if I use the below, it will work.

New-PSDrive -Name ‘W’ -PSProvider FileSystem -Root $Dest -Persist

But I feel, that is not a best practice and need to pass the credential within New-PSDrive command.

Please help me to resolve the issue.

PS version : 4
OS: windows 2008R2 standard


Welcome to the forums.
when you post code, error messages, sample data or console output format it as code, please.

Here you can read how that works: Guide to Posting Code.

You can go back and edit your existing post. You don’t have to create a new one. :wink:

Thanks in advance.

If that’s a daily task I’d consider to set up a scheduled task and set it up to run this task with the credentials you need to access the remote server. This way you don’t need to care about the credentials inside the script and you can use UNC paths instead of error prone drive letters.

Regardless of that: Windows Server 2008R2 is out of support for more than 1 year. You should urgently update to a supported version.

1 Like

I have noticed that using PowerShell remotely against an IP address instead of a name has forced me to pass credentials. Can you use the DNS name instead of the IP address to the destination?

Are you missing a \ or is that just at typo?

That worked!!!

Changed from $Dest = “\\TestData\ to $Dest = “\\TestData worked…

Thank you all for the support