是否有使用默认值与读取主机的单行? [英] Is there a one-liner for using default values with Read-Host?

查看:80
本文介绍了是否有使用默认值与读取主机的单行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这样的东西来指定提示的默认值.

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
    }

可以进一步缩短吗?

这是我的尝试.

$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.

注意$defaultValue 应该独立于一个班轮存储.类似于上面的例子.

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.

编辑;

也许我应该说一个短语而不是一行?我添加了这个编辑澄清,而我看到使用的一些答案使用分号.

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.

推荐答案

我能想到的最短版本:

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

此版本不必使用 else.

This version doesn't have to use else.

这篇关于是否有使用默认值与读取主机的单行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆