【问题标题】:Simple increment/decrement counter简单的递增/递减计数器
【发布时间】:2013-03-27 15:23:56
【问题描述】:

我想在 PowerShell 中制作一个简单的计数器。它必须提示用户他们想要更高或更低的数字。

起始数字必须为0,并且不能小于0或大于10。如果用户想要更大的数字,则必须将数字增加1,如果小于则减少1。那么它必须是能够停在所需的数字。有了这个数字,我可以设置一个注册表值。

我不知道提示用户的有效方法。我可以使用Read-Host cmdlet 来询问他们输入的是“更高”还是“更低”,但有没有更有效的方法来完成此操作?

例如,

$i = 0

while (($i -gt 0) -or ($i -lt 10)){
    $j = Read-Host "The current number is $i, would you like a higher/lower number, or quit?"

    if ($j -eq "higher") {
        $i++
        Write-Host "The current number is $i"
    } elseif ($j -eq "lower") {
        $i--
        Write-Host "The current number is $i"
    } elseif ($j -eq "quit") {
        Write-Host "Final number is: $i"
        break
    }
}

我该怎么做?

【问题讨论】:

  • 效率掌握在操作者手中。如果我在控制台 (PowerShell) 环境中工作,弹出如下建议的对话框效率较少,因为这意味着我必须将一只手从键盘上移到鼠标上(如果对话框上的键盘快捷键不明显)。为什么不为“higher”和“lower”添加别名,例如“l”和“h”和/或 up/down 和/或 u/d?其他注意事项:嵌套 if/else 语句中有很多冗余。在$j 上使用switch 进行递增/递减并保存输出以供循环结束。

标签: powershell counter increment decrement


【解决方案1】:

您可以使用是/否提示窗口来获取用户输入。

$a = new-object -comobject wscript.shell
$intAnswer = $a.popup("Do you want to delete these files?", 0, "Delete Files", 4)
If ($intAnswer -eq 6) {
    $a.popup("You answered yes.")
}
else {
    $a.popup("You answered no.")
}

如果您替换 popup() 函数的第四个参数中的“3”,您将在提示窗口中获得“是”、“否”和“取消”按钮。

参考:Provide a Yes/No Prompt in Windows PowerShell

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2020-08-02
    相关资源
    最近更新 更多