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:
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 = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Demo application" Height="350" Width="525"> <Grid> <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"/> </Grid> </Window> '@
The code copied from Visual Studio also contains the following:
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication2" mc:Ignorable="d"
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: