PowerShell scripts are very useful when it comes to automating many administrative tasks on a computer. However, sometimes the programmer needs the script to do more than just process data and carrying out its tasks in the background. Sometimes the programmer needs the script to obtain information from the script’s user. For example the script may need to know:
- the name and location of a database to be accessed
- the user’s password
- the name of a file to be processed
These cannot be hard coded into a script because they may vary according to the particular task and who’s running the script and so the programmer must find some way of obtaining the information from the user. This can be done in a few ways:
- user prompts from the script itself
- command line arguments
- user input files
The programmer can also pass information back to the user by:
- outputting text to the screen
- writing information to a file
On the other hand, the programmer may just want to obtain key pieces of information from the user as the script progresses.
Outputting Text to the Screen from a PowerShell Script
Many PowerShell cmdlets will display their output to the screen directly. For example the PowerShell “Get-Process” will display the details of all of the currently running processes (as shown in figure 1 as the bottom of this article). However, the programmer can output text to the screen by using the Write-Host cmdlet:
Having told the user what is about to happen the programmer can go about the task of eliciting the required information from that user.
Reading Text from the Screen into a PowerShell Script
The programmer can read in user responses by using the Read-Host cmdlet:
In this example the user’s answer is stored in the $op_file variable (and the short conversation can seen in figure 2).
Command Line Parameters
Although this technique is useful for talking users through a process it can seem a bit long-winded for anyone used to the system. It may, therefore, be useful to accept all of the information when the script is called. The programmer does this by making use of the args array. The args array contains all of the parameters entered on the command line. For example:
If the script file is saved as c:\powershell\input then the information would be entered on the command line as:
And the result of this can be seen in figure 3.
Combining User Inputs
The final step is, of course, to combine both means of obtaining the user input. That means checking to see if a command line argument has been entered. If it hasn’t then the user is prompted for the required information:
If this is run in a script file (as shown in figure 4) then the user is allowed to either enter the file name when they call the PowerShell script or they can wait for the script to prompt them.
Further Reading
How to Write a PowerShell Script