PowerShell脚本复制以连字符开头的文件失败,如何解决?
解决Robocopy复制以“-”开头文件的参数错误问题
问题原因
Robocopy会将以-开头的文件名误判为命令行参数,而非待复制的目标文件名,因此抛出Invalid Parameter #3错误。
解决步骤
1. 核心修改点
在Robocopy命令中添加--作为参数终止标记,告诉Robocopy后续内容均为文件名,不再解析为参数。同时修正日志路径的错误(原路径\Z:RedirectedDesktop\test_log1.txt应为Z:\RedirectedDesktop\test_log1.txt)。
2. 修改后的完整脚本
$newstreamreader = New-Object System.IO.StreamReader("Z:\RedirectedDesktop\TextDocuments\Hyphen.txt") # 源文件路径列表文件 $eachlinenumber = 1 while (($readeachline = $newstreamreader.ReadLine()) -ne $null) { $string1 = "Y:\" + $readeachline # 源文件完整路径 if (Test-Path -Path $string1) { $LogFile = "Z:\RedirectedDesktop\LogFileCheckPresent.txt" # 文件存在日志 $Message = $readeachline + ",True" $Message >> $LogFile $string2 = "Z:\RedirectedDesktop\Sample" # 目标目录 $string3 = Split-Path $readeachline -leaf $string1 = $string1.substring(0, $string1.LastIndexOf('\')) Write-Host "$string1" Write-Host "$string2" Write-Host "$string3" # 关键修改:添加--标记参数结束,避免-开头文件名被识别为参数 $execution = robocopy $string1 $string2 "--" $string3 if ($execution -match 'ERROR') { $execution | Out-File "Z:\RedirectedDesktop\test_logerror.txt" -Encoding ascii -Append # 错误日志 } else { # 修正路径错误:原路径格式无效,改为正确的Z:\开头路径 $execution | Out-File "Z:\RedirectedDesktop\test_log1.txt" -Encoding ascii -Append # 成功日志 } } else { $LogFile = "Z:\RedirectedDesktop\LogFileCheckNotPresent.txt" # 文件不存在日志 $Message = $readeachline + ",False" $Message >> $LogFile } Write-Host "$eachlinenumber $readeachline" $eachlinenumber++ } $newstreamreader.Dispose()
3. 修改说明
--参数终止符:Robocopy支持该标记,标记后的内容会被强制识别为文件名,彻底避免以-开头的文件被误判为命令参数。- 日志路径修正:原代码中
\Z:RedirectedDesktop\test_log1.txt是无效路径,调整为标准的盘符+路径格式,确保日志能正常写入。
内容的提问来源于stack exchange,提问作者Beqadar
相关产品推荐
相关产品推荐

