February 17th, 2016

PowerTip: Prompt user for value but provide default

Doctor Scripto
Scripter

Summary: Cloud & Datacenter Management MVP, Thomas Rayner, shows how to set a variable to a default value in PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to prompt a user for a value for a variable, but provide a default value if the user doesn’t enter anything?

Hey, Scripting Guy! Answer First prompt the user for the value to the variable and then detect if the response was empty. If the response is empty, set the value of the variable. You can validate parameters for a function more conveniently than this. This code is for inline variables in an interactive script:

$Interesting = Read-Host -Prompt ‘Give me a value [some-value]’

if ([string]::IsNullOrWhiteSpace($Interesting))

{

$Interesting = ‘some-value’

}

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.

Feedback