Powershell 'runspace' 不从 Powershell 控制台 运行

Powershell 'runspace' does not run from the Powershell console

我试图理解为什么这段代码会 运行 在 Powershell ISE 中而不是在 Powershell 控制台中

function close-window (){
    # close
    $hash.window.Dispatcher.Invoke("Normal",[action]{ $hash.window.close() })
    # clean up
    $powershell.EndInvoke($handle) | Out-Null
    $runspace.Close() | Out-Null
    $powershell.Dispose() | Out-Null
}

    $hash = [hashtable]::Synchronized(@{})
    $runspace = [runspacefactory]::CreateRunspace()
    $runspace.ApartmentState = "STA"
    $Runspace.ThreadOptions = "ReuseThread"
    $runspace.Open()
    $runspace.SessionStateProxy.SetVariable("hash",$hash)
    $Powershell = [PowerShell]::Create()
    $powershell.AddScript({ 
    $xaml = [xml]@"
        <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window" Title="Splash Screen" WindowStyle="None" WindowStartupLocation="CenterScreen"
        Width="499" Height="272" BorderBrush="#FF2AA0F1" ShowInTaskbar = "False" AllowsTransparency="True"
        ResizeMode = "NoResize" BorderThickness="1" >
    </Window>
"@

    $reader = New-Object System.Xml.XmlNodeReader $xaml
    $hash.window = [Windows.Markup.XamlReader]::Load($reader)
    $hash.window.Add_MouseRightButtonUp({ $hash.window.close() })
    $hash.window.ShowDialog()
})

    $Powershell.Runspace = $runspace
    $handle = $Powershell.BeginInvoke()

运行 它来自 ISE,您会得到 XAML window 出现的预期结果。 保存文件并从控制台 运行 它并静默失败 将其复制并粘贴到控制台中,它会自动失败。

它包含一个带有同步哈希表的 运行 空间 因为它是 XAML,所以我将 运行 空间作为单线程单元启动。 当 运行ning 从控制台尝试了 MTA 和 STA

目的是将这段代码用作启动画面的一部分。

脚本缺少对任何程序集名称的引用,这不是 ISE 中的问题,但控制台需要。

 Add-Type -AssemblyName PresentationCore, PresentationFramework