PowerShell Mini-Scripting Games 2014: Answer 5

Doctor Scripto

Summary: Here is the answer to Problem 5 in Windows PowerShell Mini-Scripting Games 2014. Microsoft Scripting Guy, Ed Wilson, is here. It is time for the answer to Problem 5 in Mini-Scripting Games 2014. Last week, I posted the complete Problem 5 description and task outline.

Problem 5 synopsis

Your manager has tasked you to help a junior admin with a script. It appears that the junior admin wants to solicit input from the user when the script is running. Then based on the input from the user, the script will do something else.

Answer

There are many ways of obtaining input from the user. One way to do it is to create parameters for a Windows PowerShell function, and then when the function is called, the input is gleaned. You can also use VBScript style input boxes or other tools. But to me, the easiest way to do it is to use the Read-Host cmdlet. To use the Read-Host cmdlet, all I do is specify a value for the Prompt, and store the results in a variable. I can then use that variable later.

Note  It can be dangerous to provide an unchecked input box, so it is a good idea to implement some checks for validity of the data that is input. In this example, I ask for the name of a process, and I supply a couple of valid examples for the syntax. I store the inputted data in the $a variable.

$a = Read-host -Prompt “Process to start: ex. notepad / calc” I now do a simple check to see if the inputted data matches notepad or calc. If it does, I pass the value of $a to the Start-Process cmdlet. Otherwise, I state that I cannot start the process. Here is the complete script:

$a = Read-host -Prompt “Process to start: ex. notepad / calc”

if($a -match ‘notepad’ -or $a -match ‘calc’)

    { Start-Process $a }

ELSE { “cannot start the $a process”}    Note  This is a very rudimentary example and a very basic check. It would be rather easy to work around this
   type of check. That is all there is to solving Problem 5. The answer to the final question will arrive in a few hours in the PowerTip, at which time Mini-Scripting Games Week will conclude. Join me tomorrow for more cool Windows PowerShell stuff. I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace. Ed Wilson, Microsoft Scripting Guy

0 comments

Discussion is closed.

Feedback usabilla icon