7.3. Fill In the Blanks: Take Input from the ConsoleEarly on, we looked at the distinction between interactive mode and script mode when using MSH: one expects line-by-line interaction at the console; the other can run in a completely automated fashion. However, some situations demand a middle ground in which a script is able to stop and wait for user input before processing continues. Let's look at how to use the read-host cmdlet from within a script to gather input from the console. 7.3.1. How Do I Do That?Starting with something very simple, let's look back at the "Hello, World" example. Example 7-3 contains a script that uses read-host to put information into a variable. Example 7-3. HelloWorldInput.msh$name=read-host "Name: " write-host "Hello, $name!" On running the script, the shell will wait indefinitely at the Name: prompt, waiting for some input: MSH D:\MshScripts> .\HelloWorldInput.msh Name: Andy Hello, Andy! Well-written scripts should be able to accommodate different types of invocation. A script that always blocks and waits for user input is not going to be effective running as a Scheduled Task, for example. When feasible, it is a good idea to support input from the command line and prompt only when none is found with a small modification to the original script, as shown in Example 7-4. Example 7-4. HelloWorldInput2.msh$name=$args[0] if ($name -ne "") { $name=read-host Name: } write-host "Hello, $name" It's also worth mentioning that many cmdlets define mandatory parameters . By classifying parameters as mandatory, the cmdlet author is stating that the cmdlet cannot perform its task without having this information provided. An example of this is the get-content cmdlet, which requires at least one path from which to gather content. Calling the cmdlet with no parameters will generate an explicit prompt asking for the required information: MSH D:\MshScripts> get-content Cmdlet get-content at command pipeline position 1 Supply values for the following parameters: (Type !? for Help.) Path[0]: 7.3.2. Where Can I Learn More?The built-in help for read-host provides usage information, additional detailed support for different prompt formats, and a mechanism for capturing sensitive information such as a password. |