I’ve said it once and I’ll say it again, just because you can create a fancy GUI to run your tool doesn’t mean you need to. There are a number of built in alternatives that allow you to accept user input, show command progress, and display results in a way that is fully supported and doesn’t require you spending time building out an entire user interface. Today we’re going to look at 3 commands that you can leverage to achieve this:
-
Show-Command
-
Write-Progress
-
Out-GridView
Show-Command:
Show-Command is a built in cmdlet that displays any command in a graphical window and allows you to manually enter parameters. If we simply need to get the computer name of the machine we want to execute our code on we can create a basic function for this:
function Get-Computer{
Param(
[String]
$ComputerName
)
if($ComputerName.Trim() -eq ""){
$ComputerName = $env:COMPUTERNAME
} else {
$ComputerName = $ComputerName.Trim()
}
$ComputerName.ToUpper()
}
Then when you need to accept input simply call it with Show-Command, however this cmdlet only builds your syntax for you, if we want to actually execute it we need to pipe to Invoke-Expression:
$Computer = Show-Command Get-Computer -PassThru | Invoke-Expression
Just like that you have an easy way to accept user input without going through the fuss of building out any custom UIs.
Write-Progress:
This is one of my favorite cmdlets to use because it can be as simple or as complex as you need it to be. If you are not familiar with it you might get a bit lost trying to use the parameters initially, so I suggest starting with a basic display of an executing task. Simply put Write-Progress before and after your running code:
Write-Progress "Checking ping status of remote machine..."
$PingCheck = Test-Connection -ComputerName $Computer -Count 3 -Quiet
Write-Progress " " -Completed
What if you want to get more in-depth and use this as a progress bar? You can do that as well by leveraging the PercentComplete or SecondsRemaining parameter for longer running operations.
Out-GridView:
Out-GridView is a cmdlet that can be used both to accept user input and display results. The parameters allow you to set it to single or multiple inputs. My only 2 complaints are that you can’t change the window size and it isn’t always obvious to users that you can ctl + click to select multiple if it is enabled. Here is a quick example how you could interactively kill a running process:
$RunningProcesses = Get-Process | Select-Object ProcessName, ID, CPU
$ProcessToKill = $RunningProcesses | Out-GridView -Title "Running Processes - Select a process to end" -OutputMode Single
Stop-Process -Id $ProcessToKill.Id
Note: If you are only displaying results you will want to use the Wait parameter or you will run into issues with your console trying to end before the window is displayed.