PowerShell speaks WPF and that means you can build a XAML-based GUI for your PowerShell script. It’s easy to do – here’s a small demo:
Add-Type -AssemblyName PresentationFramework [xml]$XAMLForm = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="XAML Form" Height="150" Width="320"> <Canvas> <Label Content="Simple XAML Form. Click button to exit." HorizontalAlignment="Left" Height="30" Margin="10,10,0,0" VerticalAlignment="Top" Width="275" FontWeight="Bold" FontSize="14"/> <Button Name="btnClose" Content="Close Window" HorizontalAlignment="Center" Height="30" Margin="10,50,0,0" VerticalAlignment="Center" Width="128" ClickMode="Press"/> </Canvas> </Window> "@ $NodeReader = (New-Object System.Xml.XmlNodeReader $XAMLForm) $Window = [Windows.Markup.XamlReader]::Load($NodeReader) $CloseButton = $Window.FindName("btnClose") $CloseButton.Add_Click({$Window.Close()}) $Window.ShowDialog()
Pretty straightforward. Step one is to tell PowerShell to load the PresentationFramework .NET Assembly. Step two is to build the XAML layout. Step three is to construct the XAML reader. Once you have your form built and readable by PowerShell, create variables for any XAML controls that need an event handler. Use the $Window.FindName()
method to link to the named XAML control. Once linked, add your event handler to the variable using the block format. In this demo, that happens at $CloseButton.Add_Click({$Window.Close()})
. All of your event handlers need to be positioned between constructing the XAML Reader and calling ShowDialog()
.
It’s also possible to use Visual Studio to design more complex XAML layouts, but there are some extra steps to clean it up enough for PowerShell to read it. It’s also worth repeating, at this time PowerShell only interprets WPF, so this only works on Windows-flavored PowerShell.
Leave a comment