#PowershellBasics: Get input using Read-Host

Leave a comment

February 5, 2020 by Kenneth Fisher

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,154 other followers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: