远程会话中向目标服务器复制文件/文件夹的脚本问题排查
问题排查与解决方案
核心问题分析
- 变量名错误:脚本里使用了未定义的
$filePath和$installerPath,实际应该对应你声明的$remoteFolder和$remoteFile -FromSession参数误用:这个参数是用来从远程会话复制文件到本地机器的,但你的需求是在远程服务器上,从共享目录复制到该服务器本地,完全不需要这个参数,反而会导致逻辑混乱- 凭据创建错误:
$pwd是明文字符串,必须转换成SecureString才能正常创建PSCredential对象 - 共享权限问题:远程服务器执行复制时,使用的是你创建会话的凭据,要确保该账号有权限访问
\\path\to\remote\server这个共享目录
修正后的代码
$servers = Get-ADComputer -Filter * -SearchBase "OU=Test,OU=2ndOUT,DC=domain,DC=com" | Select-Object Name -ExpandProperty Name $user = "domain\user" # 将明文密码转为SecureString格式 $securePwd = ConvertTo-SecureString "pwd" -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $securePwd foreach ($server in $servers) { $psSession = New-PSSession -Computername $server -Credential $cred $targetFile = "C:\path\to\file" Invoke-Command -Session $psSession -ErrorAction Stop -ScriptBlock { if (-Not (Test-Path $Using:targetFile -PathType Leaf)) { $targetFolder = "C:\folder\path" if (-Not (Test-Path $targetFolder)) { Write-Host "文件夹不存在,将从远程共享复制到当前服务器" $remoteSharedFolder = "\\path\to\remote\server\folder" $remoteSharedFile = "\\path\to\remote\server\file" $destination = "C:\folder\on\session\server" # 先确保目标目录存在,避免复制失败 if (-Not (Test-Path $destination)) { New-Item -Path $destination -ItemType Directory | Out-Null } # 直接在远程服务器上执行共享到本地的复制 Copy-Item -Path $remoteSharedFile -Destination $destination Copy-Item -Path $remoteSharedFolder -Destination $destination -Recurse } else { Write-Host "文件夹已存在" } } else { Write-Host "$($Using:targetFile) 已存在" } } # 用完会话记得关闭,避免资源占用 Remove-PSSession $psSession }
替代解决方案
如果Copy-Item仍然出现问题,可以试试以下两种更稳定的方法:
1. 使用Robocopy工具
Robocopy是Windows自带的专业复制工具,对共享目录复制、权限处理和错误重试更友好,直接在远程会话中调用即可:
# 替换原代码中的Copy-Item部分 robocopy $remoteSharedFolder $destination /E /COPYALL /R:3 /W:5 robocopy $remoteSharedFile $destination /COPYALL /R:3 /W:5
参数说明:
/E:复制所有子目录(包括空目录)/COPYALL:复制文件的所有属性和权限/R:3:复制失败时重试3次/W:5:每次重试间隔5秒
2. 直接通过管理员共享复制
如果共享目录访问有障碍,可以跳过共享,直接通过远程服务器的C$管理员共享复制文件:
# 在foreach循环的Invoke-Command之前执行 $localSourceFolder = "本地要复制的文件夹路径" $localSourceFile = "本地要复制的文件路径" # 直接复制到远程服务器的目标路径 Copy-Item -Path $localSourceFolder -Destination "\\$server\C$\folder\on\session\server" -Recurse -Credential $cred Copy-Item -Path $localSourceFile -Destination "\\$server\C$\folder\on\session\server" -Credential $cred
内容的提问来源于stack exchange,提问作者coolsport00
相关产品推荐
相关产品推荐

