Bite Size Bytes

Small coding solutions to big problems


Using XAML (WPF) To Build A PowerShell GUI

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Me

As a seasoned IT professional, I have developed an extremely well-rounded breadth and depth of knowledge and an exceptional ability to decipher and communicate complex issues. I have years of proven experience in IT leadership roles, security auditing, digital forensics, and overseeing development of custom applications, rounded out with a Bachelor of Science degree in Information Technology emphasizing Software Development. Over the course of my career, I have successfully held certifications as a GIAC Certified Incident Handler (GCIH), as well as CIW, CompTIA, and assorted Microsoft programming and networking certs. I have presented at the 2019 CETPA Conference in Anaheim and the 2021 CITE Conference in Sacramento.

Codementor badge