Bart Simons


A 1 post collection

Create GUI windows with PowerShell and XAML

 •  Filed under powershell, gui, xaml, scripting

GUI windows bring modern ways of interaction to your application and that is simply great: daily used applications like web browsers and e-mail client are all part of it. PowerShell has been proven to be great for automating tasks, but don't you sometimes want to bring GUI interaction to your script?

Visual Studio has great built-in functionality to design and create XAML layouts for your application:

XAML Designer in VS

The workflow is easy: just fill your form with items from the toolbox and copy all the XML code inside the XAML text editor. Start with a new PowerShell file,

Start with a new PowerShell file, and start with pasting the XML inside an PowerShell XML object like this:

[xml]$XAMLMain = @'
        Title="Demo application" Height="350" Width="525">
            <Label x:Name="label" Content="PowerShell + XAML demo application." HorizontalAlignment="Center" Margin="38,10,37.4,0" VerticalAlignment="Top" RenderTransformOrigin="1.056,1.635" Cursor="" FontSize="24" FontWeight="Bold"/>
            <Border BorderBrush="Black" BorderThickness="1" Height="238" Margin="20,57,20,0" VerticalAlignment="Top"/>

The code copied from Visual Studio also contains the following:


One can strip these tags out of the copied code safely, the script won't run with this code included, so that's why this is necessary.

Next up is creating the code that launches the form. Append the following code to the end of the PowerShell file:

$reader=(New-Object System.Xml.XmlNodeReader $XAMLMain)
$windowMain=[Windows.Markup.XamlReader]::Load( $reader )

$windowMain.ShowDialog() | out-null

Run the code, and you should be presented with a form like this: