PowerShell远程操作时如何获取完整语言模式权限
解决方法
方案1:远程执行预签名的脚本内容
你的签名证书已被远程主机信任时,约束语言模式会自动为受信任签名的代码授予完整语言模式权限,可按如下步骤操作:
- 首先在本地将需要远程执行的
$scriptblock导出为.ps1脚本文件,用你的证书对该脚本签名:
# 本地获取你的代码签名证书,替换为对应证书指纹 $codeSignCert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object Thumbprint -eq "你的证书指纹" # 导出脚本块为本地临时文件 $scriptblock.ToString() | Out-File .\temp_remote_script.ps1 -Encoding utf8 # 对脚本进行签名 Set-AuthenticodeSignature -FilePath .\temp_remote_script.ps1 -Certificate $codeSignCert # 读取已签名的完整脚本内容 $signedScriptContent = Get-Content .\temp_remote_script.ps1 -Raw
- 调整远程会话执行逻辑,传递已签名内容到远程执行:
$remote_session = New-PSSession -computername $FromHost # 远程执行已签名脚本内容 Invoke-Command -Session $remote_session -ScriptBlock { param($signedContent, $argsList) $tempPath = Join-Path $env:TEMP "remote_signed_$(Get-Random).ps1" $signedContent | Out-File $tempPath -Encoding utf8 & $tempPath $argsList Remove-Item $tempPath -Force } -ArgumentList $signedScriptContent, "xxxxx" # 复制文件操作不受语言模式限制,可直接按原逻辑执行 Copy-Item -FromSession $remote_session "C:\xxxx\$FileName" "C:\yyyyy\$FileName" -verbose Remove-PSSession $remote_session
方案2:创建绑定信任证书的专属远程端点(适合批量操作场景)
如果需要频繁操作该类主机,可提前在远程主机上注册自定义PowerShell会话配置,仅允许持有指定证书的请求获得完整语言模式权限:
- 首次配置需要在远程主机本地用管理员权限执行如下命令:
# 替换为你的证书指纹 $allowedCertThumbprint = "你的证书指纹" # 注册自定义会话配置 $sessionParams = @{ Name = "TrustedSignedAccess" SecurityDescriptorSddl = "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)" LanguageMode = "FullLanguage" RestrictedRemoteServer = $false } Register-PSSessionConfiguration @sessionParams # 配置该端点仅接受受信任签名的代码请求 Set-Item WSMan:\localhost\Shell\TrustedHosts -Value $allowedCertThumbprint -Force Restart-Service WinRM -Force
- 后续连接时指定该自定义端点即可直接获得完整语言模式权限:
# 连接时指定自定义会话配置 $remote_session = New-PSSession -computername $FromHost -ConfigurationName "TrustedSignedAccess" # 后续Invoke-Command、Copy-Item操作无需调整,直接按原逻辑执行即可
注意事项
- 远程主机PowerShell版本需至少为5.1,部分低版本PowerShell对约束模式下的签名代码权限判断存在已知异常
- 确认你的代码签名证书已导入远程主机的
受信任的发布者证书存储区,否则签名脚本仍会被拦截
内容的提问来源于stack exchange,提问作者Tim Brigham
相关产品推荐
相关产品推荐

