Blog Post

#PowershellBasics: Get input using Read-Host

,

Conditions are the life blood of programming. This condition is met so now I need to do this task. That condition is met so I need for the program to end. Typically we are going to use parameters or calculate information to be used in the condition, but sometimes we want human input. Fortunately this is pretty easy with Powershell.

$ShouldI? = Read-Host -Prompt 'Well should I?'
If ($ShouldI? -eq 'Y') {
    Write-Host 'I did some stuff.'
 } Else {
    Write-Host 'I didn''t do anything.'
}

Well should I?: Y

I did some stuff.

Pretty simple. The only down side is that this means the code can’t be automated. How about if we want the option of getting human input, or allow for information to be passed in automatically.  Again, not too hard. We just combine Read-Host with a parameter.

param
(
    $ShouldI? = (Read-Host -Prompt 'Well should I?')
)
If ($ShouldI? -eq 'Y') {
    Write-Host 'I did some stuff.'
 } Else {
    Write-Host 'I didn''t do anything.'
}

Now, if I call this script without passing it a parameter I get prompted. If I include a parameter then I don’t get prompted.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

4 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

4 (1)

You rated this post out of 5. Change rating