AWS PowerShell自定义SSO回调提示无可用Runspace运行脚本如何解决
PowerShell 7 AWS SSO回调报错解决方案
问题根因
AWS .NET SDK触发SsoVerificationCallback回调时使用的是未绑定PowerShell Runspace的后台线程,直接把PowerShell脚本块转为Action委托传入的话,后台线程无法执行脚本块逻辑,就会抛出如下错误:
There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type.
最优解决方案
使用纯.NET实现的回调逻辑替代PowerShell脚本块,通过Add-Type内联C#代码实现打开浏览器的逻辑,完全避开脚本块依赖Runspace的问题。
修改后的可运行脚本如下:
$ErrorActionPreference = "Stop" Import-Module -Name "AWSPowerShell.NetCore" $profileName = "my-sso-profile" # 内联编译C#回调逻辑,纯.NET实现不需要PowerShell Runspace $awsSdkPath = (Get-Module AWSPowerShell.NetCore).Path | Split-Path | Join-Path -ChildPath "AWSSDK.Core.dll" Add-Type -TypeDefinition @" using System; using System.Diagnostics; using Amazon.Runtime; public static class SsoCallbackHelper { public static readonly Action<SsoVerificationArguments> OpenBrowserCallback = (args) => { Process.Start(new ProcessStartInfo(args.VerificationUriComplete) { UseShellExecute = true }); }; } "@ -ReferencedAssemblies $awsSdkPath # 原有凭证获取逻辑 $chain = New-Object Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain $credentials = $null $chain.TryGetAWSCredentials($profileName, [ref]$credentials) $ssoCredentials = [Amazon.Runtime.SSOAWSCredentials]$credentials $ssoCredentials.Options.ClientName = "Example-SSO-Script" # 替换为C#实现的回调委托 $ssoCredentials.Options.SsoVerificationCallback = [SsoCallbackHelper]::OpenBrowserCallback Set-AWSCredential -Credential $ssoCredentials # 验证凭证有效性 Get-StsCallerIdentity
轻量替代方案(不推荐生产使用)
如果不想引入C#代码,也可以手动为会话设置默认Runspace,但是该方案存在并发冲突风险:
# 脚本开头添加该配置 if (-not [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace) { [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = [PowerShell]::Create().Runspace }
内容的提问来源于stack exchange,提问作者Philip Pittle
相关产品推荐
相关产品推荐

