PowerShell InputBox
The other day I gave you a function to create a VBScript style message box in PowerShell. If you find yourself needing MsgBox in PowerShell, you’re likely going to want InputBox. This too is accomplished using the [microsoft.visualbasic.interaction] class. You’ll need to load the assembly first if you haven’t already.
PS C:\> [reflection.assembly]::loadwithpartialname(”microsoft.visualbasic”) | Out-Null
PS C:\> [microsoft.visualbasic.interaction]::Inputbox(”enter something”)
As in VBScript you can also specify a title and a default value. Here’s a more complete function you could call and an example.
1: Function Show-Inputbox {
2: Param([string]$message=$(Throw "You must enter a prompt message"),
3: [string]$title="Input",
4: [string]$default
5: )
6:
7: [reflection.assembly]::loadwithpartialname("microsoft.visualbasic") | Out-Null
8: [microsoft.visualbasic.interaction]::InputBox($message,$title,$default)
9:
10: }
11:
12: $c=Show-Inputbox -message "Enter a computername" `
13: -title "Computername" -default $env:Computername
14:
15: if ($c.Trim()) {
16: Get-WmiObject win32_computersystem -computer $c
17: }
Executing the sample code will give you this inputbox:
The inputbox’s return value is whatever you enter. What you need to do, as I’ve done, is add code to validate the data.
$c=Show-Inputbox -message “Enter a computername” `
-title “Computername” -default $env:Computername
if ($c.Trim()) {
Get-WmiObject win32_computersystem -computer $c
}
In my example I only use the value in the Get-WMIObject expression if $c has a value. I used the Trim() method to remove any spaces. It’s possible a user could accidentally enter space somewhere so using Trim cleans that up.
Download this sample here
Tags: function, Inputbox, powershell, scripting, VBScript








August 18th, 2008 at 5:29 pm
FYI, SAPIEN’s PowerShell extensions snap-in has a Read-InputBox cmdlet, too. Same basic effect, and an easy way to see how to write cmdlets since the source code’s simplistic.
August 19th, 2008 at 5:40 am
I probably should have mentioned that. For those interested, you can download SAPIEN’s Powershell extensions at http://www.primalscript.com/Free_Tools/index.asp.