hashtable.ContainsKey永远不会评估为true?

时间:2019-12-18 14:08:59

标签: powershell powershell-core

我有以下代码,该代码读取XML文件,输出节点并向用户显示输入选择的提示。由于某种原因,无论我输入什么内容,它始终显示“无效选择”。我在做什么错了?

$buildsFile = [System.Xml.XmlDocument](Get-Content "$($config.remotebuildspath)/builds.xml");
$builds = $buildsFile.builds;

$i = 0
$buildHash = @{}
Write-Host "Available Builds: " -ForeGroundColor Green
ForEach ($buildVersion in $builds.ChildNodes) {
    $i++
    Write-Host "(" -NoNewline  -ForeGroundColor Green
    Write-Host $i -NoNewline
    Write-Host ") $($buildVersion.LocalName)"  -ForeGroundColor Green
    $buildHash.add($i, $buildVersion.LocalName)
}
$isValid = $false
do {
    Write-Host "Choose: " -NoNewline -ForeGroundColor Green
    $choice = Read-Host
    if ($buildHash.ContainsKey($choice)) {
        $isValid = $true
    } else {
        Write-Host "Invalid Choice!" -ForeGroundColor Red
        $isValid = $false
    }
} while ($isValid -eq $false)
Write-Host "You picked ${$buildHash[$choice]}"

调试器屏幕截图:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

基于@Jeroen Mostert的评论,我在[int]$choice语句中添加了if。为了避免在非数字输入上引发错误,我还合并了this answer中的辅助函数Is-Numeric

这是我的最终代码:

function Is-Numeric ($Value) {
    return $Value -match "^[\d\.]+$"
}

$buildsFile = [System.Xml.XmlDocument](Get-Content "$($config.remotebuildspath)/builds.xml");
$builds = $buildsFile.builds;

$i = 0
$buildHash = @{}
Write-Host "Available Builds: " -ForeGroundColor Green
ForEach ($buildVersion in $builds.ChildNodes) {
    $i++
    Write-Host "(" -NoNewline  -ForeGroundColor Green
    Write-Host $i -NoNewline
    Write-Host ") $($buildVersion.LocalName)"  -ForeGroundColor Green
    $buildHash.add($i, $buildVersion.LocalName)
}
$isValid = $false
do {
    Write-Host "Choose: " -NoNewline -ForeGroundColor Green
    $choice = Read-Host
    if (Is-Numeric $choice) {
        if ($buildHash.ContainsKey([int]$choice)) {
            $isValid = $true
        } else {
            Write-Host "Invalid Choice!" -ForeGroundColor Red
            $isValid = $false
        }
    } else {
        $isValid = $false
        Write-Host "Please enter a number!" -ForegroundColor Red
    }
} while ($isValid -eq $false)
Write-Host "You picked ${$buildHash[$choice]}"
相关问题