powershell - 为什么按 "Enter"相当于数字0?

标签 powershell

我不明白为什么按 Enter 键和按键盘上的 0 是一样的。

[int] $Choice = -1
$Count = 2

while ($Choice -lt 0 -or $Choice -gt $Count)
{
    Write-Host "Input number"
    $Choice = Read-Host

    Write-Host "choice:"
    Write-Host $Choice

}

即使直接按回车,输出也将是 0。我希望用户明确输入 0。

最佳答案

在第一个声明中:

[int] $Choice = -1

...您将 $choice 类型转换为 [int]

当您将强制转换应用于赋值的左侧(变量名称的左侧)时,PowerShell 会将其“记住”为类型约束,并将该变量视为强类型 - PowerShell 将尝试将您分配给 $choice 的任何内容从那里转换为 [int]

在没有任何其他输入的情况下按提示符中的 Enter 会导致 Read-Host 返回空字符串(如 "")

转换逻辑将空字符串视为 $null,并将 $null 转换为 [int] 得到值 0 。您可以通过直接将空字符串转换为 [int] 来看到这一点:

PS C:\> [int]""
0

如果您明确需要一个数字,您可能应该在分配给 $Choice 之前验证来自 Read-Host 的输入:

$inputString = Read-Host
if($inputString -notmatch '^\d+$') {
    Write-Host "Digits only please!"
    continue
}

关于powershell - 为什么按 "Enter"相当于数字0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60249679/

相关文章:

powershell - “$xyz”和“Write-Host ” $ xyz “”提供不同的输出

Powershell 2 和 .NET : Optimize for extremely large hash tables?

powershell - IIS条件网址重写匹配类型的Powershell脚本

Powershell 别名位置

Powershell 传递命令开关作为变量

powershell - 搜索注册表并创建新项目

Powershell ISE 缺少颜色输出

powershell - Powershell-使用.htm文件作为电子邮件正文

powershell - 如果 powershell 中为空,则删除文件中的一行

PowerShell Get-Service 返回结果很慢