3

我正在使用下面的 PowerShell (v7) 脚本来自定义 AWS SSO 登录流程。它基于有效的 .net 实现:

$ErrorActionPreference = "Stop"
Import-Module -Name "AWSPowerShell.NetCore"

$profileName = "my-sso-profile"

$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"
$ssoCredentials.Options.SsoVerificationCallback = [System.Action[Amazon.Runtime.SsoVerificationArguments]]{
    param($x)
    # Launch SSO Login Flow in Browser
    Start-Process $x.VerificationUriComplete
}

Set-AWSCredential -Credential $ssoCredentials
# Print details about current Credential
Get-StsCallerIdentity

错误

当我在 Powershell (v7) 中运行此脚本时,出现异常:

此线程中没有可用于运行脚本的运行空间。 您可以在 System.Management.Automation.Runspaces.Runspace 类型的 DefaultRunspace 属性中提供一个。您尝试调用的脚本块是: param($x) ...cationUriComplete

看起来在调用我的脚本委托时出现问题$ssoCredentials.Options.SsoVerificationCallback

问题

如何配置我的脚本/PowerShell 会话,以便我的SsoVerificationCallback委托执行而不会引发错误?

研究

我猜这个问题与调用 SsoVerificationCallback 委托的 C# 代码有关,它现在是一个 PSScriptBlock(?),并且在 C# 和 PowerShell 之间来回编组出现问题。

环顾 SO,SsoVerificationCallback调用不是 Async,尽管它是在 async method 内部调用的GetSsoTokenAsync,所以我不认为Runspace issus using async APIs from Powershell适用。

而且我没有直接拨打网络电话,因此请在博客中提供提示,例如https://www.agilepointnxblog.com/powershell-error-there-is-no-runspace-available-to-run-scripts-in-this -thread/推荐的设置[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null也没有产生任何影响。

4

1 回答 1

1

虽然我不清楚细节,但以下一般信息可能会有所帮助:

虽然 PowerShell脚本块 ({ ... })通常可以用作.NET 委托,但它们的调用只有在调用线程具有与之关联的 PowerShell 运行空间时才能成功 - 否则脚本块无法执行。

如果从 PowerShell 会话自己的前台线程调用(返回)给定的基于脚本块的委托,则根据定义满足此要求;例如,将脚本块作为MatchEvaluator委托传递给[regex]::Replace()

PS> [regex]::Replace('woo', 'o$', { param($m) $m.Value + 't!' })
woot!

但是,在您的情况下,似乎另一个线程(一个没有关联的 PowerShell 运行空间的线程)正在调用您的基于脚本块的委托,这会导致您看到的错误。

可能有一个基于 C# 代码的临时编译的繁琐、重要的解决方法,如this answer所示。

于 2021-11-03T03:37:41.620 回答