I've written something like this to specify default values for prompts.
$defaultValue = 'default'
$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"
if ($prompt -eq "") {} else {
$defaultValue = $prompt
}
Can it be shortened further?
Here is my attempt.
$defaultValue = 'default'
$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"
if (!$prompt -eq "") {$defaultValue = $prompt}
I want a one-liner, so I'm gonna hold out accepting an answer until then.
N.b. $defaultValue
should be stored independently of the one liner. Similar to the example above.
I've accepted the answer which lead me to the solution I was looking for.
$defaultValue = 'default'
if (($result = Read-Host "Press enter to accept default value $defaultValue") -eq '') {$defaultValue} else {$result}
And for those of you asking why. The reason is because it is easier on the eyes of whoever comes after me. Less is always more, when clarity is not sacrificed. IMHO.
EDIT;
Instead of a single line, perhaps I should have said a single phrase? I've added this edit clarify whilst a few answers I have seen use are using a semi-colon.
Description. The Read-Host cmdlet reads a line of input from the console (stdin). You can use it to prompt a user for input. Because you can save the input as a secure string, you can use this cmdlet to prompt users for secure data, such as passwords.
A: You can prompt for user input with PowerShell by using the Read-Host cmdlet. The Read-Host cmdlet reads a line of input from the PowerShell console. The –Prompt parameter enables you to display a string of text. PowerShell will append a colon to the end of the string.
In PowerShell, the input can be retrieved from the user by prompting them with Read-Host Cmdlet. It acts as stdin and reads the input supplied by the user from the console. Since the input can also be stored as secured string, passwords can also be prompted using this cmdlet.
Use Read-Host to Enable the press any key to continue in the PowerShell. Read-Host is the most common method to prompt user input. You can use this method to pause the execution when prompting user input in the PowerShell. After pressing the key, you need to press Enter to exit the pause mode.
$defaultValue = 'default'
$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"
$prompt = ($defaultValue,$prompt)[[bool]$prompt]
If you absolutely have to have it in one line:
$defaultValue = 'default'
($defaultValue,(Read-Host "Press enter to accept the default [$($defaultValue)]")) -match '\S' |% {$prompt = $_}
Shortest Version I could came up with:
if (!($value = Read-Host "Value [$default]")) { $value = $default }
This version doesn't have to use else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With