Reputation: 415
I am trying to understand why this code will run in the Powershell ISE but not from the Powershell console
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()
Run it from the ISE and you get the expected result of a XAML window appearing. Save the file and run it from the console and it fails silently Copy and paste it into the console and it fails silently.
It contains a single runspace with a synchronised hashtable Because it is XAML, I start the runspace as a single threaded apartment. When running from the console have tried MTA and STA
The aim is to use this piece of code as part of a splash screen.
Upvotes: 2
Views: 1643
Reputation: 415
The script was missing references to any assembly names, not a problem in the ISE but required for the console.
Add-Type -AssemblyName PresentationCore, PresentationFramework
Upvotes: 1