r/PowerShell • u/adbertram • 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.
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
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
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
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
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
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
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
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
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.
1
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 mouseupclick and you are done.
Hate me if you want but Powershell is sometimes really arcane and over complicated.
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....