PowerShell + XAML => GUI

You can use WPF GUI from PowerShell using the following snippet

Add-Type -AssemblyName PresentationFramework

$xaml = [xml] @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="My window" Height="300" Width="300">
    <Grid>
        <Button x:Name="okButton" Content="OK" />
    </Grid>
</Window>
"@

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

$okButton = $form.FindName("okButton")

$okButton.add_Click({
    $form.Close()
})

$form.WindowStartupLocation = "CenterScreen"
$form.ShowDialog();

UPDATE:
I found that this will work out of the box only in PowerShell 3.

In previous versions of PowerShell it will fail on line #13

The problem is with STA.

According to this

-Sta
Starts Windows PowerShell using a single-threaded apartment. In Windows PowerShell 3.0, single-threaded apartment (STA) is the default. In Windows PowerShell 2.0, multi-threaded apartment (MTA) is the default.

So if you want to use GUI from PowerShell 2 host you have to start it in STA mode

PowerShell.exe -Sta

PowerShell ISE is in STA already.

Here I’ve got an advice to write in your script something like

if([System.Threading.Thread]::CurrentThread.ApartmentState -ne "STA") {               
    Write-Host -ForegroundColor Red "RUN PowerShell.exe with -Sta switch"
    Write-Host -ForegroundColor Red "Example:"              
    Write-Host -ForegroundColor Red "    PowerShell -noprofile -Sta C:\scripts\YourGUIUtility.ps1"                
}
Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s