LEARN with scripting TRAINING CREATE with SCRIPTING TOOLS SHARE in a COMMUNITY BUY Scripting Products

SAPIEN Solutions

SAPIEN homepage
SAPIEN Software
PrimalScript script editor+ide
PrimalScope script debugger
Free Tools script utilities
SAPIEN Press tech books
ScriptingAnswers.com learn+share
ScriptingOutpost.com online store
Blog.Sapien.com official blog
Contact Us

 

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:

pshinputbox

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

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Technorati Tags: , , , ,

Tags: , , , ,

2 Responses to “PowerShell InputBox”

  1. Don Says:

    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.

  2. Jeffery Hicks Says:

    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.

Leave a Reply


Entries (RSS) and Comments (RSS).