r/PowerShell • • Aug 26 '19

How to Build a PowerShell GUI for your Scripts

Hey guys, June Castillote just wrote a shiny new PowerShell blog post you may enjoy.

Summary: Learn how to build a PowerShell GUI with a little PowerShell and free Visual Studio in this step-by-step walkthrough.

https://adamtheautomator.com/build-powershell-gui?utm_source=redditpowershell&utm_medium=social&utm_campaign=newblogpostnotifications

179 Upvotes

55 comments sorted by

22

u/taylorblakeharris Aug 26 '19 edited Aug 27 '19

This is definitely not anything new, but it's still good information nonetheless.

A few years back, I created a XAML/PowerShell GUI from scratch for controlling an SCCM operating system deployment task sequence and it has radically changed the way we do things around here. Probably the most productive bit of code I've ever seen implemented by myself anywhere. I mainly did it to experiment, not because I actually believed it would be incredibly useful, but really learning the intimate details of task sequences SCCM OSD opens up so many possibilities using these interfaces.

For example, in addition to creating check-boxes for all software that is needed on the computer during deployment, I created a tab that accepts another computer name, detects the installed software, and matches it with any available software in the menu automatically, preventing the need to ever reference the original machine when doing a replacement. All of this is happening from WinPE, mind you! It was as simple as making a two-column grid in the WPF app and a simple line in PowerShell to use WinRM/Get-CimInstance to get the installed software on the machine! Example below (redacted for identifying information):

https://imgur.com/xkMi8Oc

So simple yet so useful....

8

u/arcadesdude Aug 26 '19

I'm interested in the tool you made. Do you have a link?

3

u/NotAWooosh Aug 27 '19

I would also check out UI++ for a dynamic UDI. I’m not sure how this tool compares without seeing it

2

u/taylorblakeharris Aug 27 '19

UI++ is no doubt a robust tool. When I first set out to use an OSD menu, I considered it, but I finally decided to do it all from scratch for the sake of learning PowerShell (I was new to it at the time a few years ago) and more about the SCCM task sequence as well. There were also some more specific, bespoke features I needed for my company environment so I was able to make them myself. They wouldn't have been so easy to integrate with the UI of UI++.

One thing I really like about UI++ is how it directly queries SCCM for existing applications and packages in your library and populates the menu from them. For now, I have to manually create CheckBox entries for each application I want available in my menu and bake them in directly, but I'd love to figure out how they're doing this and implement it myself. I think they're using some sort of custom web service that runs on the SCCM MP and can gather that data and send it in object format to the client.

I think the main thing that he wants is the specific feature I added to scan a remote computer's installed software and automatically enable the application options in the menu that correspond, making new PC replacement just a smidge easier.

2

u/taylorblakeharris Aug 26 '19

I haven't created a generic, extensible version that offers an interface for you to customize yourself like some of the better known tools out there for this purpose, but I'd be happy to share some of the key constructs and code with you.

I assume you're wanting to create a menu that displays during an SCCM task sequence, allowing the user to customize the deployment right? What kind of options are you wanting to put into it? Application selection? Options to add AD group/OU memberships? Sending a notification email at the end?

Depending upon how custom you want it to be for your environment and purposes, you may prefer to design the UI yourself inside of Visual Studio. From there though, I can definitely help with driving it's functionality with PowerShell backend and the necessary SCCM task sequence steps.

2

u/abetzold Aug 27 '19

I'm interested in the way you queried the software then matched it to a package or application in SCCM. About to do a desktop refresh and this would be fantastic

4

u/taylorblakeharris Aug 27 '19

I'd be happy to help!

Do all of your machines have the ConfigMgr client installed? I ask because there's a MUCH better WMI class for querying installed software than Win32_Product but it's only available from the SCCM client's hardware inventory features.

Win32_Product is incredibly slow and only returns products that are installed with an MSI and registered with Windows Installer. It takes anywhere from 30 seconds to 2 minutes to run!

SMS_InstalledSoftware returns nearly instantly because it essentially just enumerates all of the registry entries for Programs and Features in the control panel. Not only is it faster, but it includes all installed software, not just MSI packages.

I'll send you the basic outline in the morning when I get to work.

Apart from designing the GUI bits, it really is simpler than you'd think. It's just getting the SMS_InstalledSoftware class from a remote machine via Get-CimInstance and then a switch statement for all of the software names you want to match for against what's in the returned list. Then in the scriptblock for each condition, just enable the corresponding checkbox or add the name to a variable.

2

u/abetzold Aug 27 '19

Yes I have config manager deployed. Appreciate you sharing!

2

u/w3lbow Aug 27 '19

FWIW, we used SCCM as a source of info during an IBM audit. They were happy with us doing direct SQL queries on the SCCM database to find out where their software was installed.

1

u/jajeff Aug 27 '19

Could you please send me an outline as well?

1

u/taylorblakeharris Aug 27 '19

Sure. I'm working on cleaning up a more generic outline of everything for the guy above. I'll be sure and share it with you as well.

1

u/ihartmacz Aug 28 '19

Could you send it to me, too? Please?!? :)

1

u/taylorblakeharris Aug 28 '19

Which part do you need? Just the software detection bit?

2

u/taylorblakeharris Aug 27 '19

Not sure what happened to the screenshot I posted here.... I'll have to re-upload it tomorrow.

1

u/SgtLionHeart Aug 27 '19

This seems like a superb concept, and I'd be really interested in a high-level overview of how you put this together.

3

u/taylorblakeharris Aug 28 '19 edited Aug 28 '19

Thanks! Let me know if this summary isn't detailed enough:

The gist of the application as a whole is (or at least, when I started the project, it was) essentially just a friendly tool that runs from WinPE at the beginning of a Task Sequence (TS) for recording user/technician input into TS variables that can be referenced in TS step conditions to control the outcome of an OS deployment/configuration. For example, I create a checkbox in the menu for every application I've published in SCCM, and if the box is checked, then the menu creates a TS variable for that piece of software set to a value of "True", signaling the TS to install that application during deployment.

With that concept in mind, the software detection bit is very straightforward:

  1. In the GUI, create a section (I chose to make a separate tab) that contains a text box for the host name of the remote machine to scan installed software on, along with a button to submit the host name and start the scan.

  2. In the click event for your software scan button, open a CIM session to the remote machine using the following command:$CimSession = New-CimSession -ComputerName $SoftwareSourceHostname -Credential (Get-Credential) -SessionOption (New-CimSessionOption -Protocol Dcom)Notice the DCOM protocol option here... This is a requirement, as WinPE does not suppot WinRM or PowerShell remoting unfortunately, so relying on DCOM is the only way to make this work. The good news is that it will still work even against older machines running PowerShell 2.0 even though they don't support the CIM cmdlets.

  3. With the CIM session open, get the list of all installed software using the SCCM client's SMS_InstalledSoftware class:$InstalledSoftwareClass = Get-CimInstance -CimSession $CimSession -Namespace root\cimv2\sms -ClassName SMS_InstalledSoftwareThe SMS_InstalledSoftware class shows everything you'd see in the Control Panel, not just MSI packages like Win32_Product, and takes about 2-4 seconds max to run, which is great.

  4. Finally, the menu option matching part. Perform a foreach loop on all of the installed software products, and inside of the loop, just place a single -wildcard switch statement against the $_.ProductName property with a switch case for every piece of software you have an option for in your menu. This construct will look something like this:

ForEach ($application in $InstalledSoftwareClass)
{
    switch -wildcard ($application.ProductName)
    {
        "7-Zip*"                   {$Install7Zip_CheckBox.IsChecked = $true}
        "Adobe Flash*"             {$InstallFlash_CheckBox.IsChecked = $true} 
    "Adobe*Reader*"            {$InstallReader_CheckBox.IsChecked = $true} 
    "*Acrobat XI Standard"       {$InstallAcrobat_CheckBox.IsChecked = $true}
        "Google Chrome"                  {$InstallChrome_CheckBox.IsChecked = $true}
        "Java*"                    {$InstallJava_CheckBox.IsChecked = $true}
        "WebEx*"                   {$InstallWebEx_CheckBox.IsChecked = $true} 
    "*Office 2016*"              {$Office2016_CheckBox.IsChecked = $true}
    }
}

These parts are optional, but I usually display a MsgBox to the user of the menu when it finishes, showing a list all of the items that were detected and matched. I also created a ListView grid in my Software tab that I add all of the detected software items to (whether they match available apps or not) with two columns: ProductName and ProductVersion. In my XAML for the ListView, I bind the columns to these property names. That way I can just add the list of all software in $InstalledSoftwareClass to $ListView.ItemsSource and get a nice Control Panel like interface for showing everything installed on the specified remote machine.

Something else you may find helpful, I make all of my checkbox item names end in "_CheckBox" so that I can store all of them as TS variables in a single line:

Get-Variable -Name "*_CheckBox" | ForEach-Object {Set-TSVariable -Name ($_.Name -split "_")[0] -Value $_.Value.IsChecked}

Obviously Set-TSVariable is an internal function I made to call the COM object methods. Also, all of my checkboxes for applications that will be installed start with "Installxxxxx_Checkbox", so I can then use the same logic as above to isolate all of my software options in the menu, loop through them, and for the ones that are true, record their value in a dynamic application install list with the same base variable names so the TS will install them.

5

u/Hoggs Aug 26 '19

Nice... I figured this would be a repeat of other articles on the subject, but the loop to create variables based on control names is a great idea. Brings it a bit closer to writing WPF in C#!

4

u/taylorblakeharris Aug 26 '19

His code that sets variables matching the form object names is the same code that has been floating around since people have been making XAML GUI's with PowerShell. It just looks foreign because he split the usual one-liner into a few lines for a try/catch. Probably better this way though.

0

u/[deleted] Aug 26 '19

[deleted]

3

u/WadeEffingWilson Aug 26 '19

Theres no benefit (not sure about it slowing down a script or not, but it would be negligible, if so) other than its just a neat and compressed way to create numerous variables that differ in a predictable way.

You can call each variable on it's own line, one at a time, or you can loop through a range and create numerous variables through each iteration.

1

u/taylorblakeharris Aug 27 '19

Or you can use a workflow and use the foreach -parallel to loop through them all at once :D

1

u/WadeEffingWilson Aug 27 '19

I wonder how efficient that ends up being. Does the program need to interpret, index, and initialize the entire loop, then pass off a task to separate processes, and then receive an all-done command with status info? How does that compare to just creating global variables?

1

u/taylorblakeharris Aug 27 '19

I was actually being facetious haha. I don't think that would be efficient at all, and I'm not even sure that the Windows Workflow components are present in WinPE where I use most of these apps that I make.

0

u/[deleted] Aug 26 '19

[deleted]

2

u/WadeEffingWilson Aug 26 '19

No worries. I use that method when I program microcontrollers and Im iterating through pin groups.

1

u/Hoggs Aug 27 '19

In C# (where WPF was intended to be used), all form controls with Names automatically become root variables. So you can:

TextBoxFirstName.Text = "Value"
TextBoxLastName.Text = "Value"

So it's a lot more familiar for anyone coming from C#.

It's also a pain in the arse to keep writing:

$MainWindow.FindName('TextBoxFirstName').Text = "Value"
$MainWindow.FindName('TextBoxLastName').Text = "Value"

2

u/needssleep Aug 27 '19

Make it a function?

shortname("Value")

5

u/JeremyLC Aug 26 '19

I just recently posted code that does the same thing with XaML, and I included a link to Brian Posey's Article from which I got the original code.

That said, have an upvote for encouraging people to use WPF/XaML.

4

u/stuartall Aug 26 '19

Haven't looked but I've been meaning to try implement a GUI for helpdesk facing scripts and I'm looking forward to trying this out tomorrow.

Thanks!

4

u/Jofiseen Aug 26 '19

Useful too after creating your GUI to use a wrapper program to create an .exe from it. ps2exe is pretty good for this.

3

u/ka-splam Aug 26 '19

Something I haven't seen is using SharpDevelop for the GUI builder; it's a much smaller download and install than Visual Studio.

Anyone used it?

The GUI designer bit has been split off and is MIT licensed - https://github.com/icsharpcode/WpfDesigner - soooo it might be possible to wrap into a module on the PS Gallery .. right?

2

u/BobMilli Aug 27 '19

Hello,
WPF seems to be the right path to follow and so I've tried SharpDevelop and unfortunately it crash every time I try to switch to design mode with the following error : " Value cannot be null. Parameter name: path1 - E:\Test.xaml:1" and I must be dummy but I don't see how to use WdfDesigner from the Gihub repo you've provided.

3

u/get-postanote Aug 27 '19

Adam's a good source, but...

Don't wite full GUI's if you don't have to or unless explicitly told to do so. It's potentially unnedded extra work, UI arguments, usability arguments, accessibility needs arguments, maintenance, etc.

You can use PowerShell built-in stuff and never need to write custom form (WF/WPF) code at all.

Then there other drag adn nddrop tool, for purchase (Sapine's PowerShell Stuidio, PowerShell Pro Tools add on for for Visual Studio/VSCode/PowerShell) free (poshgui.com and eventemplate on the MS powershellgallery.com) to use if needed.

Examples:

The Out-GridView Cmdlet - https://technet.microsoft.com/en-us/library/ff730930.aspx

Creating a Simplistic GUI Interface with Out-GridView - https://mikefrobbins.com/2014/09/11/creating-a-simplistic-gui-interface-with-out-gridview

Creating a GUI Using Out-GridView in PowerShell - https://mcpmag.com/articles/2016/02/17/creating-a-gui-using-out-gridview.aspx

Fun with PowerShell's Out-GridView - https://mcpmag.com/articles/2013/01/08/pshell-gridview.aspx

Poor Man’s GUI - https://powershell.getchell.org/2018/02/13/poor-mans-gui

Show-Command - PowerShell for GUI admins? - https://4sysops.com/archives/show-command-powershell-for-gui-admins

Tag Archives: Out-Gridview (A PowerShell Core Out-Gridview Solution)

https://jdhitsolutions.com/blog/tag/out-gridview

https://jdhitsolutions.com/blog/tag/out-gridview/page/2

https://www.reddit.com/r/PowerShell/comments/b3q0qo/id_like_to_create_a_simple_active_directory_query

2

u/RICHUNCLEPENNYBAGS Aug 27 '19

This is cool, but these always end up looking so gnarly that I wonder if you wouldn't be happier just doing a pure C# thing.

2

u/taylorblakeharris Aug 28 '19

They end up looking this way because most of the people making them, myself included, are not exactly app or interface developers and they're basically putting things together just enough to get a job done and serve a purpose. There's really no reason that making applications this way can't look and function just as good as a WPF application written with C#. I mean, loading and interacting with WPF objects from .NET within PowerShell, or loading and interacting with the same WPF objects from .NET with C# has no bearing on the way that the app renders visually. It all comes down to design experience and knowledge, and the XAML is the same either way. The main differences are going to be performance.

To get a multi-threaded interface that doesn't freeze every time your script is still waiting to exit an event's script block with PowerShell has to be done by creating and managing runspaces manually which is truthfully quite painful. If you make a native C# WPF app, the code behind and interface are automatically handled by the framework in their own separate runspaces for you, with no extra attention required. That being said, just doing things as simple as querying CIM can be painful in C# compared to the conciseness in PowerShell syntax, and that's kind of the opportunity cost. It really depends on the scope of your app and how much time you have to plan/design it.

2

u/RICHUNCLEPENNYBAGS Aug 28 '19 edited Aug 28 '19

I don't mean the way the UI looks; I mean more that PowerShell code for GUI applications looks hairy/unnatural to write.

You can run PowerShell from C#; that might be another option to consider too.

2

u/taylorblakeharris Aug 28 '19

That seems even less efficient than using PowerShell to interact with UI's. There's so much overhead with PowerShell to make it work as seamlessly as it does.

2

u/RICHUNCLEPENNYBAGS Aug 28 '19

I doubt it's really significant, especially when you already have to have the .NET Framework.

2

u/senorezi Aug 26 '19

https://poshgui.com/Editor is also easy to use

5

u/JeremyLC Aug 26 '19

That generates WinForms code, which is, in my opinion, not desirable.

4

u/taylorblakeharris Aug 27 '19

I completely agree. WPF is vastly superior. Especially once you learn how to use data bindings. It's amazing how small your resulting PowerShell code can end up being once you've bound everything.

3

u/nepronen Aug 27 '19

WPF version of Poshgui is close to beta release :)

2

u/WadeEffingWilson Aug 26 '19

I predominantly use WinForms and it works great for putting a GUI together with minimal time and effort.

4

u/taylorblakeharris Aug 27 '19

I have to agree with JeremyLC... Using WPF is going to be vastly superior. It completely separates your GUI code from your PowerShell logic code, because you don't have a bunch of PowerShell lines setting all of the individual properties of each WinForm object just to define your GUI. It's all neatly defined in a separate XAML file (or integrated here-string if you prefer) and just 3-4 lines of PowerShell read in your GUI code and load it all. The rest is all of your logic or interacting with the controls via code.

3

u/JeremyLC Aug 26 '19

A WPF Designer will produce your XamL and the code to load/render it is minimal. The actual controls are programmed almost identically to WinForms. The plus is that WPF is much more powerful, you get DPI scaling, GPU acceleration (so useful for a PoSH script! :P ), and you can even inline SVG (Inkscape actually has a "Save As... XaML option), which is really nice if you want to add visual elements to your UI that aren't just controls. (I've done this)

Personally, I just like WPF better because the resulting code feels cleaner. It has a distinct separation of presentation and processing. You can even store the XaML externally to your script. It's also easier to make layout changes because you can just tweak the XaML and, as long as you don't rename any controls, you don't have to update the processing code at all. (I've done this, too)

1

u/WadeEffingWilson Aug 27 '19

When first learning about Powershell GUIs, I explored WinForms and WPF. I was a little pushed off by the requisite inclusion of XaML and while I had a lot of experienced with structured mark-up, I felt it was an unnecessary step in learning a GUI framework.

I did enough during research to understand what was gained by WPFs use of XaML, but, to me, it was fluff and further complicated matters when trying out the new territory. Don't get me wrong, I've seriously considered scrapping projects done in WinForms and redoing them in WPF because of its versatility and the fact that WinForms was either too restrictive or it couldn't do exactly what I wanted. In the past, I have done some fairly neat and hacky ways of creating custom form objects in WinForms but I understand that WPF streamlines that process.

I like to do all of my development from scratch and I tend to stay away from bloated IDEs. I'm not usually a fan of something that autogenerates code as it feels like a missed opportunity to learn. However, with that said, I'll give the WPF Designer a shot and see what I've been missing out on.

Thanks for the info!

0

u/[deleted] Aug 27 '19

[removed] — view removed comment

1

u/WadeEffingWilson Aug 27 '19

My decision was based on the availability of other languages. I don't have many choices at my job, so I worked with what I've got.

1

u/[deleted] Aug 27 '19

[removed] — view removed comment

1

u/WadeEffingWilson Aug 27 '19

I agree, somewhat. While there are situations where a particular language absolutely has to be used over any others that are available, most modern languages are versatile enough to handle just about anything.

Certain ones shine in specific areas (python does well with large amounts of data and numbers, C/C++ work well in constrained PLC environments, etc) but when it comes to writing a UX/UI driven widget or application, there doesn't really seem to be an obvious language (considering desktop/non-web). Java has swing & AWT, C# has UWP & WPF, C++ can use Qt, Python has tkinter, so there's a ton of options and using one over the other doesn't really have specific advantages. It comes down to what is available and what the developer feels most comfortable with.

I disagree that compiled > interpreted languages for anything more than N number of lines. That sounds like the paradox of the heap--what number of lines does it take to cross between staying with an interpreted language and redoing it in a compiled language? What about using a compiled language for something that has relatively few lines? Also, what about python's ability to be compiled?

Contextually, I'm a Security Engineer but while I come from a varied background, I'm predominantly a Software Engineer. At work, I don't have access to an IDE and more versatile languages. What I do have access to are Powershell and Python. For DevOps/SRE (something extra I do to make my job easier), both languages are great for automation. Also, if I want to extend the usage out to, say, an analyst, I can throw together a GUI while still retaining the operational code.

Personally, I love Powershells (.NETs, really) ability to leverage the native Windows GUI framework. It's more versatile than using a console driven interface and, while I understand that there's better ways to meet that same end goal, I wouldn't denigrate a neat feature found in a scripting language.

On top of everything else, it's a great way for an ambitious SysAd to break into some minor dev work and learn about front-end development.

1

u/JeremyLC Aug 27 '19

In this context, the biggest advantage of PoSH over c# is that you have your choice of so many fine wheels that you don't have to reinvent. That is, many vendors now have PoSH modules for their software or hardware to make management and automation easier. Plus, there are modules for automating so many things on Windows, and even some of the stuff in PS Core, that all this would be a pain to have re-invent in C#. I think your choice of UI/UX tool comes down to target platform and users more than language.

1

u/jhizzle4rizzle Aug 27 '19

weird that you have to create a full on c# WPF app in Visual Studio just to make a parallel xaml file :/ I guess microsoft doesn't support this kinda thing more directly?

3

u/[deleted] Aug 27 '19

It's not necessary to create the app in Visual Studio, especially when one is adept with writing XAML from scratch using just a text editor. I used Visual Studio because of its WYSIWYG capability for this write up. It just makes it easier to show the readers the concept. :)

1

u/Fatality Aug 27 '19

If I'm doing anything more complicated than a popup box why wouldn't I just use C#/WPF?

1

u/tmrnl Aug 27 '19

Really nice! I was using Powershell Tools Pro but you have to pay for that (1 time i believe).

This looks like a nice easy way to do about the same, without paying ;)\

-edit-

Not sure if its powershell tools pro feature, or that it comes with Visual Studio, but i can also create an executable from the PS1 file.

1

u/subassy Aug 27 '19

I didn't write this and I haven't tried it yet but this may be an alternative to the PS/GUI combo. Maybe.

https://github.com/zelon88/HTA-UI

1

u/[deleted] Aug 27 '19

Holy cow... I use RunRev IDE (LiveCode.org if you want the free version), takes 15 seconds to create a GUI, and i dump the results from PS in there. No brainer, no time wasted.

Create a stack (window in Livecode), create button, create a field called "result", insert this little script into the button:

on mouseup
put shell(mypsScript.ps1) into field "result" 
or
  -- get some events from a server
  put the label of button "EventLogName" into logname
   put the label of btn "EventLogServer" into thisserver
   put the label of btn "EntryType" into entrytype
   put the label of btn "Eventid" into eventid
  
   put "Get-EventLog -LogName '" & logname &  "' -computername" && thisserver && "-EntryType" && entrytype && "-newest 100" && PSpostformat into dcmd
  put shell(dcmd) into field "result"  

end mouseup

click and you are done.

Hate me if you want but Powershell is sometimes really arcane and over complicated.