为何Get-WindowsUpdate本地可运行,通过Invoke-Command远程执行失败?
远程执行PSWindowsUpdate模块的权限问题解决
问题场景
本地通过Invoke-Command远程连接Win10Test服务器,执行以下PowerShell脚本:
$TargetServer = 'Win10Test' Invoke-Command -ComputerName $TargetServer -Credential administrator -Scriptblock { Install-Module PSWindowsUpdate Import-Module PSWindowsUpdate Get-WindowsUpdate }
报错信息
Import modules: The file "C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.3\PSWindowsUpdate.psm1" cannot be loaded because script execution is disabled on this system. For more information, see about_Execution_Policies.
ObjectNotFound: The command "Get-WindowsUpdate" was found in the module "PSWindowsUpdate", but the module could not be loaded. If you want more information, run "Import-Module PSWindowsUpdate".
已完成排查
- 目标服务器本地执行相同脚本成功
- 确认目标服务器存在PSWindowsUpdate模块,路径为
C:\Program Files\WindowsPowerShell\Modules\PSWindowsUpdate\2.2.0.3\PSWindowsUpdate.psm1 - 已在目标服务器执行
start winrm、winrm quickconfig、Enable-WuRemoting -Verbose - 曾临时设置
Set-ExecutionPolicy -ExecutionPolicy Unrestricted - 远程执行
Invoke-Command调用Get-Process命令成功
解决方法
核心原因是PowerShell本地会话和WinRM远程会话的执行策略相互独立,之前设置的Unrestricted仅对本地会话生效,远程会话的执行策略仍处于限制状态。
方案1:修改目标服务器远程会话的系统级执行策略
- 远程连接到目标服务器,执行命令查看远程会话当前执行策略:
Get-ExecutionPolicy -Scope RemoteSigned
- 设置远程会话执行策略为
RemoteSigned(推荐生产环境使用,允许本地无签名脚本运行,远程脚本需签名):
Set-ExecutionPolicy -Scope RemoteSigned -Force
若测试环境需要更宽松的配置,可替换为Unrestricted,但需注意安全风险。
方案2:仅针对当前远程会话临时设置执行策略
在Invoke-Command的脚本块中先临时设置会话级执行策略,无需修改系统配置:
Invoke-Command -ComputerName $TargetServer -Credential administrator -Scriptblock { Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned -Force Import-Module PSWindowsUpdate Get-WindowsUpdate }
内容的提问来源于stack exchange,提问作者maqz
相关产品推荐
相关产品推荐

