## Friday, 29 March 2013

### Keyboard input in Powershell

Asking users for input in Powershell is very straight-forward. Use the Read-Host cmdlet in Powershell and add a string value to the -Prompt switch of the cmdlet to specify which text to display to the user. Assign the result from Read-Host to a Powershell variable, e.g. $myvariable. This variable can then be treated logically and control the further program execution and logical flow of the program. The following code shows how this can be done: function Ask-FavoriteColor ([int]$personsToAsk){
<#
.SYNOPSIS
.DESCRIPTION
The favorite color was asked in the movie "Holy Grail"
The number of persons to ask
#>
foreach ($i in 1..$personsToAsk){

[string] $color = Read-Host -Prompt "What is your favorite color?" if ($color.ToLower() -ne "blue"){
Write-Host "You didn't say blue!"
}
else {
Write-Host "Good choice!"
}
}

}

If you see the text at the top of the function, you will see how one can document the function using meta keywords such as .SYNOPSIS and .DESCRIPTION. When using the Powershell cmdlet Get-Help, e.g. Get-Help Ask-FavoriteColor -detailed, one will see the (detailed) documentation in the Powershell help page. This is rather equivalent to the obiqutous man command seen in Unix-based systems.

When creating Powershell functions, your functions should be documented using this technique. There are lots of other meta keywords that can be used. See this overview for meta keywords for documentation.

What is your favorite color?: red
You didn't say blue!
What is your favorite color?: blue
Good choice!

'