I have a PowerShell script for backup that I used on Windows 2003 Server for a long time, and now I have a problem with it on Windows Server 2012 R2. I have this message when I try to execute it:
2019/09/18 08:40:25 ERROR 3 (0x00000003) Creating Destination Directory Z:\BACKUP\D\ The system cannot find the path specified.
I run the PowerShell script in PowerShell ISE as administrator or as a scheduled task with highest privileges. The script is executing on a server on a domain (DOMAIN1) that has the source drive and the destination is on another server on another domain (DOMAIN2). There is no trust between the domains.
When I use the
net use command it works fine with PowerShell ISE but not via scheduled task. When I use
New-PSDrive it doesn't work anywhere. I insert
GCI statement to be sure the drive is connected and it lists the content of the destination directory.
I simplified the code for debugging:
$strNetDrvPath = '\\server.domain2.local\BkpDrv' $strNetDrvUser = 'DOMAIN2\BkpUser' $strNetDrvPwd = 'ABCD1234' #net use Z: $strNetDrvPath /user:$strNetDrvUser $strNetDrvPwd $objCredential = New-Object System.Management.Automation.PsCredential -ArgumentList $strNetDrvUser, ($strNetDrvPwd|ConvertTo-SecureString -AsPlainText -Force) New-PSDrive –Name Z –PSProvider FileSystem –Root $strNetDrvPath -Credential $objCredential gci Z: -Name $strCmd = "robocopy D:\. Z:\BACKUP\D /B /MIR /NP /R:0 /LOG:D:\RC_Log.txt" Invoke-Expression $strCmd #cmd /c $strCmd #net use Z: /delete /y Remove-PSDrive Z
I left a comment with the
net use command to show what I tried. What could be the problem? Is there a another way to do it that should work?
When you want to use
New-PSDrive for mapping a Windows network drive you need to add the parameter
-Persist. From the documentation:
Indicates that this cmdlet creates a Windows mapped network drive. Mapped network drives are saved in Windows on the local computer. They are persistent, not session-specific, and can be viewed and managed in File Explorer and other tools.
New-PSDrive –Name Z –PSProvider FileSystem –Root $strNetDrvPath -Persist -Credential $objCredential
Since you provide explicit credentials
net use should work just fine from a scheduled task. If it doesn't something else is amiss (for debugging scheduled tasks see here).
Also, DO NOT USE
robocopy can be run directly from PowerShell.
$params = '/B', '/MIR', '/NP', '/R:0', '/LOG:D:\RC_Log.txt' & robocopy D:\. Z:\BACKUP\D @params
User contributions licensed under CC BY-SA 3.0