【问题标题】:Powershell 'runspace' does not run from the Powershell consolePowershell 'runspace' 不会从 Powershell 控制台运行
【发布时间】:2015-08-04 05:35:51
【问题描述】:

我试图了解为什么此代码将在 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 窗口出现的预期结果。 保存文件并从控制台运行它,它会静默失败 将其复制并粘贴到控制台中,它会静默失败。

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

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

【问题讨论】:

  • 我将其复制/粘贴到 PowerShell 控制台窗口中,它按预期显示了一个空的 WPF 窗口。
  • 你用来执行这段代码的命令行是什么?
  • 谢谢各位,你们的 cmets 帮了大忙。我在命令行中尝试了所有选项,但你能让它工作吗,我怀疑 -mta 和 -sta 是罪魁祸首,对不起,我应该把命令行放进去,下次会。知道它对其他人有效,这为我指明了正确的方向。该脚本缺少对程序集名称的任何引用,我添加了它,现在可以正常工作Add-Type -AssemblyName PresentationCore, PresentationFramework, WindowsBase, System.Windows.Forms, System.Drawing

标签: powershell runspace


【解决方案1】:

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

 Add-Type -AssemblyName PresentationCore, PresentationFramework

【讨论】:

  • 嗨 - 我遇到了和你一样的问题。但即使加载正确的程序集,我也无法让它工作。它只是打开一个 PS 窗口并再次关闭它,而不显示任何 GUI。你有没有做其他事情来让它工作?
猜你喜欢
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 2023-03-19
  • 2013-03-18
  • 2022-11-23
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
相关资源
最近更新 更多