PowerShell远程安装程序与驱动脚本无法运行,求排查思路与解决建议
你的脚本存在以下核心问题:
- 会话使用错误:调用
New-PSSession创建了远程会话但未后续使用,你后续的New-Item、Copy-Item默认都是在本地机器执行,并没有操作远程计算机 - 环境变量语法错误:PowerShell不支持CMD风格的
%systemroot%写法,需要用PowerShell格式的$env:SystemRoot,且路径前加.\会变成相对路径,无法正确定位系统根目录 - 路径不匹配:创建的驱动目录是
DriverInstallation,但复制文件时写的目标路径是DriverTransfer,路径完全对不上 - 远程变量作用域问题:
Invoke-Command的脚本块默认无法直接读取本地会话的变量,需要加$using:前缀引用本地变量 - 文件未实际传到远程:
Copy-Item没有指定远程会话参数,文件只会复制到你本地的对应目录,不会传到远程计算机 - 安装路径错误:远程执行安装时用的是你本地的文件选择路径,远程机器上不存在该路径,需要用你上传到远程的目标路径
修正后的参考脚本
$handler_submitwindow2_Click= { $Computer = Read-Host -Prompt 'Enter the Computer Name you are accessing' # 创建并保留远程会话 $remoteSession = New-PSSession -ComputerName $Computer #----------远程创建目录----------# $remoteBasePath = "$env:SystemRoot\Temp" Invoke-Command -Session $remoteSession -ScriptBlock { New-Item -ItemType Directory -Path "$using:remoteBasePath\FileTransfer" -Force | Out-Null New-Item -ItemType Directory -Path "$using:remoteBasePath\DriverInstallation" -Force | Out-Null New-Item -ItemType Directory -Path "$using:remoteBasePath\SoftwareInstallation" -Force | Out-Null } #----------拷贝本地文件到远程会话----------# # 注意:$openFileDialog1/2/3需要提前取到选中的文件/目录的完整路径 Copy-Item -Path $openFileDialog1.FileName -Destination "$remoteBasePath\FileTransfer" -Recurse -ToSession $remoteSession $remoteDriverPath = "$remoteBasePath\DriverInstallation\" + (Split-Path $openFileDialog2.FileName -Leaf) Copy-Item -Path $openFileDialog2.FileName -Destination $remoteDriverPath -Recurse -ToSession $remoteSession $remoteSoftwarePath = "$remoteBasePath\SoftwareInstallation\" + (Split-Path $OpenFileDialog3.FileName -Leaf) Copy-Item -Path $OpenFileDialog3.FileName -Destination $remoteSoftwarePath -Recurse -ToSession $remoteSession Write-Host "Software and Drivers get installed on $Computer" #----------远程执行安装----------# Invoke-Command -Session $remoteSession -ScriptBlock { Start-Process -FilePath $using:remoteDriverPath -ArgumentList "/q" -Wait } Invoke-Command -Session $remoteSession -ScriptBlock { Start-Process -FilePath $using:remoteSoftwarePath -ArgumentList "/q" -Wait } # 清理远程会话 Remove-PSSession -Session $remoteSession }
额外注意事项
- 确保运行脚本的账号有远程计算机的管理员权限,且远程计算机已开启PowerShell远程管理(可在远程机器以管理员执行
Enable-PSRemoting -Force开启) - 若
$openFileDialog1/2/3是WinForm的文件选择框对象,需要取.FileName属性才能拿到选中的文件完整路径,不要直接用对象本身 - 加
-Force参数到New-Item,如果目录已存在不会报错中断脚本 - 安装命令的静默参数
/q仅适用于支持MSI标准参数的安装包,如果你用的是其他类型的安装包(比如NSIS、Inno Setup打包的),需要对应修改静默参数
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

