PowerCLI哈希表重复键添加报错:调用Add方法参数为2时触发异常
问题修复方案
核心问题分析
- 哈希表键重复添加错误:
foreach循环中若存在多个匹配tier0_path的Tier1网关,每次循环都会调用Add方法添加相同键,而哈希表不允许重复键,因此抛出异常。 - 最终判断逻辑错误:
$testingHash.T1G存储的是匹配到的Tier1网关对象,并非布尔值,用它和$true比较永远不成立,导致匹配成功也输出错误结果。
修复步骤
1. 替换哈希表Add方法为直接赋值
用直接赋值替代Add方法,键存在时会覆盖值,不存在时自动添加,避免重复键报错:
$testingHash['T1G'] = $t1g $testingHash['IST1G'] = $true
2. 修正最终判断条件
直接判断IST1G的布尔值,或者判断T1G是否不为null,确保逻辑正确:
If ($testingHash.IST1G) { Write-Output "YES!!!" } else { Write-Output "OH NO!" }
3. 可选优化:找到匹配项后退出循环
如果只需要第一个符合条件的Tier1网关,添加break跳出循环,避免不必要的遍历:
If ($t1g.tier0_path -eq $t1t0connection) { Write-Output "t1-stretched is connected to t0-gateway-stretched" $testingHash['T1G'] = $t1g $testingHash['IST1G'] = $true break # 找到匹配项后终止循环 }
完整修复后的脚本
#I have left out the previous code where I retrieve the ID of the T0 Gateway. # #Verify if the T0 path is retrieved correctly Write-Host "========================================" Write-Host $t1t0connection Write-Host "========================================" #Get Tier 1 Gateways $resultsT1g = Invoke-WebRequest -Uri "$uri/global-manager/api/v1/global-infra/tier-1s" -Headers $header #Parse return and create an object from the results $t1gItems = ConvertFrom-Json -InputObject $resultsT1g.Content -Depth 10 -AsHashtable #Find the Tier 1 Gateway and store it in the testing hashtable foreach ($t1g in $t1gItems.results) { If ($t1g.tier0_path -eq $t1t0connection) { Write-Output "t1-stretched is connected to t0-gateway-stretched" # 替换Add方法为直接赋值,避免键重复错误 $testingHash['T1G'] = $t1g $testingHash['IST1G'] = $true # 可选:找到第一个匹配项后退出循环 break } } If ($null -eq $testingHash.T1G) { $testingHash['IST1G'] = $false Write-Error "t1-stretched is not connected to t0-gateway-stretched" } #Output pass/fail # 修正判断条件,使用IST1G的布尔值判断 If ($testingHash.IST1G) { Write-Output "YES!!!" } else { Write-Output "OH NO!" }
验证说明
- 修复后不会再出现键重复的异常,即使存在多个匹配项;
- 最终判断逻辑会根据实际匹配结果正确输出对应信息;
- 添加
break后可提升脚本执行效率,减少不必要的循环遍历。
内容的提问来源于stack exchange,提问作者I-1
相关产品推荐
相关产品推荐

