PowerShell远程复制文件及创建文件夹的凭据认证报错排查
问题排查与修复方案
报错原因分析
- New-PSDrive 报错:你要映射的路径
\\$computer\c$\Folder\尚未创建,系统找不到该网络共享路径,导致驱动器映射失败。 - New-Item 报错:FileSystem 提供器仅允许在
New-PSDrive命令中使用-Credential参数,New-Item不支持直接指定凭据,因此触发参数绑定异常。 - Remove-PSDrive 报错:由于前面的驱动器映射失败,Y盘并未创建,执行删除操作时自然提示找不到目标驱动器。
修复后的脚本
$computers = Get-Content "C:\tmp\computers.txt" $source = "C:\Folder\" $destShare = "c$" $destFolder = "Folder" $creds = Get-Credential foreach ($computer in $computers) { if (Test-Connection -ComputerName $computer -Quiet) { try { # 先映射到远程机器C盘根目录 New-PSDrive -Name Y -PSProvider FileSystem -Root "\\$computer\$destShare" -Credential $creds -ErrorAction Stop # 检查目标文件夹是否存在,不存在则创建 $remoteFolderPath = "Y:\$destFolder" if (-not (Test-Path -Path $remoteFolderPath)) { New-Item -ItemType Directory -Path $remoteFolderPath -ErrorAction Stop | Out-Null } # 执行文件复制 Copy-Item -Path $source -Destination $remoteFolderPath -Recurse -ErrorAction Stop Write-Output "$computer - 文件复制成功" | Out-File "C:\tmp\_Copy_success.txt" -Append } catch { Write-Output "$computer - 操作失败: $_" | Out-File "C:\tmp\_Copy.txt" -Append } finally { # 无论成功失败,清理映射的驱动器 if (Get-PSDrive -Name Y -ErrorAction SilentlyContinue) { Remove-PSDrive -Name Y -Force } } } else { Write-Output "$computer 离线" | Out-File "C:\tmp\_Copy_error.txt" -Append } }
关键修改说明
- 调整映射逻辑:先映射到远程机器的C盘根目录(
\\$computer\c$),而非未创建的子文件夹,避免因路径不存在导致映射失败。 - 移除无效参数:通过已映射的Y盘操作远程文件夹,不再给
New-Item指定-Credential参数,绕过该命令不支持凭据的限制。 - 完善错误处理:使用
try/catch/finally块统一捕获异常,确保操作完成后清理映射的驱动器,避免残留。 - 增加存在性检查:用
Test-Path判断目标文件夹是否存在,减少不必要的创建操作。 - 细化日志输出:新增成功日志文件,方便区分不同机器的操作结果。
内容的提问来源于stack exchange,提问作者Arbelac
相关产品推荐
相关产品推荐

