My Code: InputLine function for WSH (Inputbox for CScript)

Now that I’m color-coded, I may start a regular feature here where I publish smallish code bits I’ve written…

For WSH scripters out there, here’s a handy one I wrote…

To explain, for GUI-type WSH scripts (usually run under the WScript engine), VBScript has a native Inputbox function, which prompts for user input via a dialog box.  Command-line-type scripts (running under CScript) have no command-line equivalent, though — yes Inputbox works, but a GUI dialog doesn’t really fit a command-line script.

So to fill that gap, I wrote this:

' Name:		InputLine
' Desc:		like Inputbox, but for use with cscript
' Author:	Rob Eberhardt, www.slingfive.com
' Params:	prompt as string, default value as string
' Returns:	user's answer
' History:
'		2005-06-13	added default param
'		2005-02-28	created original InputLine function
FUNCTION InputLine(p_strPrompt, p_strDefault)
	call Wscript.Echo(p_strPrompt & ":")
	IF p_strDefault<>"" THEN CreateObject("WScript.Shell").SendKeys(p_strDefault)
	DIM strInput
	Do While Not WScript.StdIn.AtEndOfLine
		strInput = strInput & WScript.StdIn.Read(1)
	Loop
	WScript.StdIn.skip(2)
	InputLine = strInput
END FUNCTION

Example usage:

DIM strChoice
strChoice = InputLine("Enter favorite color", "Red")
call WScript.Echo("You entered: " & strChoice)

…which would look like this from a command-line:

Enter favorite color:
Red
You entered: Red

For bonus points, you can detect if the current engine is CScript or WScript, and use InputLine or InputBox appropriately (like if you’re note sure what engine will run your code):

DIM strChoice

'detect CSCRIPT context & use InputLine
IF Instr(lcase(wscript.FullName), "cscript")>0 THEN	
	strChoice = InputLine("Enter favorite color", "Red")

ELSE	'detect WSCRIPT context & use native InputBox
	strChoice = InputBox("Enter favorite color", "Color?", "Red")

END IF

call WScript.Echo("You entered: " & strChoice)

Hope someone can use it.

Note: I would have absorbed this engine detection logic into a single smart InputLine-like function, if only Javascript supported Inputbox, or VBScript supported optional arguments.  But, InputBox’s optional 2nd “Caption” param makes no sense with InputLine, and unfortunately the languages leave no room to gracefully work around that.

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>