Search code examples
powershellrefactoring

Is there a one-liner for using default values with Read-Host?


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.


Solution

  • Shortest Version I could came up with:

    if (!($value = Read-Host "Value [$default]")) { $value = $default }
    

    This version doesn't have to use else.