You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Robocopy自动将源目录设为脚本所在目录的问题求助

Robocopy镜像源路径异常问题解决

问题背景

  • 脚本目录:PowerShellScripts(原位于C盘桌面,后迁移至D:\根目录下)
  • 脚本文件:Dbackup.ps1
  • 预期镜像源:D:\(本地硬盘分区根目录)
  • 预期镜像目标:F:\D_LAPTOP_BACKUP_...(USB外接SSD分区)

脚本在C盘目录下以管理员模式运行时完全正常,但迁移到D:\PowerShellScripts目录后,同样以管理员模式运行,Robocopy实际使用的镜像源变为D:\PowerShellScripts,而非预期的D:\。控制台打印的commandString显示源路径参数正确,但实际执行结果不符合预期。

脚本代码

[string]$currentDirectory = Get-Location
[DateTime]$currentDateTime = Get-Date

[string]$currentTimeStamp = $currentDateTime.ToString("yyyy-MM-dd_HH-mm-ss")
[string]$currentDayStamp = $currentDateTime.ToString("yyyy-MM-dd")

[string]$sourcePath = "D:"
write-host "Source Path: " $sourcePath

[string]$destinationDrive = "F:"
[string]$destinationFolderName = "\D_LAPTOP_BACKUP_"
[string]$destinationPath = $destinationDrive + $destinationFolderName + $currentDayStamp
write-host "Destination Path: " $destinationPath

[string]$logFile = ""
[string]$logFileExtenstion = ".txt"
$logFile = $currentDirectory + $destinationFolderName + $currentTimeStamp + $logFileExtenstion

write-host "Log File: " $logFile

[string]$defaultDirExclusionSet = '$RECYCLE.BIN "D:\System Volume Information"'
write-host "Dir Excluded: " $defaultDirExclusionSet

[string]$commandString = "Robocopy $sourcePath $destinationPath /MIR /R:3 /W:3 /DCOPY:DAT /COPY:DATSOU /TEE /LOG:$logFile /MT:32 /XD $defaultDirExclusionSet"

write-host $commandString

Invoke-Expression $commandString

Robocopy执行结果头信息(中文翻译版)

-------------------------------------------------------------------------------
   ROBOCOPY     ::     Windows 可靠文件复制工具                              
-------------------------------------------------------------------------------

  开始时间 : 2022年7月24日 晚上11:04:51
   源路径 : D:\PowerShellScripts\
   目标路径 : F:\D_LAPTOP_BACKUP_2022-07-24\

    文件 : *.*
        
  排除目录 : D:\System Volume Information
        
  选项 : *.* /TEE /S /E /COPYALL /PURGE /MIR /MT:32 /R:3 /W:3 

------------------------------------------------------------------------------

问题原因

在PowerShell中,单独使用盘符(如D:)时,实际指向的是该盘符下的当前工作目录,而非盘符根目录。当脚本位于D:\PowerShellScripts目录下运行时,当前工作目录就是该文件夹,因此Robocopy将D:解析为D:\PowerShellScripts,而非预期的D:\。

解决方法

修改脚本中$sourcePath变量的赋值,明确指定D盘根目录(添加路径分隔符\):

[string]$sourcePath = "D:\"

修改后,无论当前工作目录处于D盘的哪个位置,Robocopy都会正确识别源路径为D盘根目录。

内容的提问来源于stack exchange,提问作者AKSJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:42:21