Channels ▼
RSS

.NET

Building GUI Applications in PowerShell


It might seem surprising to write an article on developing UIs with PowerShell, Microsoft's souped-up command-shell scripting language, but in reality, it makes a lot of sense. As developers, we need to deliver what the user wants, and that deliverable is sometimes a GUI. Being the lazy coder, I like to get my job done in the fewest lines of code possible. It's quicker, easier, less error-prone, and simpler to maintain if it can be coded in PowerShell. To run the examples I present below, you'll need ShowUI, the PowerShell module to help build WPF user interfaces in script.

Answer: Two Lines of Code

How many lines of PowerShell are needed to create a complete working WPF application? Two! Here's the code that yields the result shown in Figure 1.

Import-Module ShowUI
Label "Hello World" -FontSize 42 –Show


Figure 1: A simple display box.

It'll take you more time using statements, an IDE, and a compilation step to get the equivalent in C#. Here, you press Enter at the end of the second line of PowerShell code and you've got a running WPF app. I'll be going deeper into building PowerShell WPF applications in this article, but if you want another angle on using PowerShell to develop WPF applications, check out my MSDN article, "Secrets to Building a WPF Application in Windows PowerShell."

In this article, I show a couple of full WPF applications that make use of ShowUI: a Twitter search GUI and a video player. First, let's code up a GUI using WinForms.

PowerShell and WinForms

PowerShell works with WinForms out of the box. Figure 2 shows a simple WinForms GUI with a button. Click the button and the date will print in the console.


Figure 2: A simple WinForm built with PowerShell.

The PowerShell script for this WinForm (Listing One) has some code worthy of further explanation. First up, a PowerShell session does not automatically load the System.Windows.Forms DLL, so we use the Add- Type -AssemblyName System.Windows.Forms method to do so. If you use PowerShell and WinForms this way, there is no built-in editor to lay out your forms, so you need to manually handle position, sizing, and event hookup. (However, SAPIEN Technologies has a product called Primal Studio that contains a tool that works like the Visual Basic Forms Editor. It lets you drag and drop controls on a designer, hook up events by double-clicking the controls, and so on. The final result is all PowerShell. The tool, while commercial, can be tried at no cost.)

Listing One: Creating a simple WinForm in PowerShell.

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object Windows.Forms.Form
$form.Size = New-Object Drawing.Size @(200,100)
$form.StartPosition = "CenterScreen"
$btn = New-Object System.Windows.Forms.Button
$btn.add_click({Get-Date|Out-Host})
$btn.Text = "Click here"
$form.Controls.Add($btn)
$drc = $form.ShowDialog()

After creating the form, I set its size and its start position. Then I create a Windows button, wire up the click event by calling the add_click() method, and pass it a PowerShell script block. I let the button's size take the default, and then I add the button to the form's Controls collection. Finally, the call to the ShowDialog() method displays the form on the screen.

Using WinForms to build GUIs has its advantages. It's available on any version of Windows, so you can e-mail a script to someone, and that person could run it and have a GUI ready to go.

Next up, I'll examine the the ShowUI module, which provides abstractions that cannot be achieved through pure markup.

Using ShowUI with the Twitter API

Being able to search social media sites quickly provides many benefits. In fact, there are companies that do this all day long, capturing details from Twitter and other social sites. After collecting all of this data, they run analytics to determine sentiment toward a product or service. While I won't get into specific analysis here, I'll show you how to query Twitter using its search API, process the XML results to easily work with the data in PowerShell, and then display it in a GUI. In less than a page of PowerShell script, I can glue together WPF and the results of a Twitter search!

When reading over this approach, keep in mind that this is not just for Twitter or social media sites with XML feeds. For example, you could use PowerShell v3 and change the search.rss to search.json. That returns a JSON string, and in PowerShell v3, you could pipe it to ConvertFrom-Json. Such a pipe would transform the data into PowerShell objects with properties that you could wire up into the ShowUI WPF application. Most sites on the Web today return either XML or JSON. They're just low-hanging fruit, waiting for a custom interface or a mashup.

The Search-Twitter function uses the search API and looks for the word "PowerShell." It accelerates the XML into an XmlDocument using [xml] and then dot-notates down to the item in the XML feed.

function Search-Twitter ($q = "PowerShell") {
   $wc = New-Object Net.Webclient
   $url = "http://search.twitter.com/search.rss?q=$q"
   ([xml]$wc.downloadstring($url)).rss.channel.item
}

Invoking the Search-Twitter function returns an array of objects, each with 32 properties on it. I'll select just two for now and look at the results.

Search-Twitter | select pubDate, title

The following data is what I get back from the search for the two selected fields:

pubDate                         title
-------                         -----
Fri, 10 Feb 2012 00:43:33 +0000 Windows PowerShell(TM) Scripting Guide
Fri, 10 Feb 2012 00:42:17 +0000 #PowerShell Use Tab Expansion in the Po
Fri, 10 Feb 2012 00:40:56 +0000 @energizedtech Captain! She canny take
Fri, 10 Feb 2012 00:37:56 +0000 Shout out to @ToddKlindt "the PowerShel
Fri, 10 Feb 2012 00:31:38 +0000 #PowerShell February PowerShell group m
Fri, 10 Feb 2012 00:29:57 +0000 RT @mattn_jp: powershell???????????????
Fri, 10 Feb 2012 00:22:32 +0000 @robinmalik: "Very excited to play arou
Fri, 10 Feb 2012 00:22:24 +0000 It seems like it is certainly going to
Fri, 10 Feb 2012 00:21:00 +0000 #PowerShell Using PowerShell v3 to cons
Fri, 10 Feb 2012 00:16:23 +0000 ????????···?????···PowerShell?????···??
Fri, 10 Feb 2012 00:16:16 +0000 Windows PowerShell v1.0: TFM, 2nd Editi
Fri, 10 Feb 2012 00:10:23 +0000 #PowerShell Windows PowerShell for Shar
Fri, 10 Feb 2012 00:08:55 +0000 Any #Powershell gurus out there that ca
Fri, 10 Feb 2012 00:08:51 +0000 ???: powershell?get-help???firefox?????
Fri, 10 Feb 2012 00:00:38 +0000 RT @ScriptingWife: R U ready for some #

This data might be useful, and so I save it to query later. But there are far more interesting fields in that data — the Twitter user's image, for example — so next let me make a little Twitter GUI app instead of just looking at raw data in this format.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Comments:

Video