我想在输出哈希表($htInput
)中使用输入哈希表($htOutput
)中的键,而不知道具体的键名只是它们的数字位置。我可以使用$counter
循环中的for
变量访问各个输入哈希表键:
$main = {
Begin {
Write-Host "SO Question Begin..." -ForegroundColor Black -BackgroundColor Green
}
Process {
try {
$htInput = @{Alpha = 1; Bravo = 2; Charlie = 3; Delta = 4; Echo = 5}
$htOutput = @()
for ($counter = 0; $counter -lt $htInput.Count; $counter++) {
$rzlt = $rzlt + $counter
$htOutput += $rzlt
}
# Expected Output: $htOutput = @{Alpha = 0; Bravo = 1; Charlie = 3; Delta = 6; Echo = 10}
# Actual Output : $htOutput = @(0; 1; 3; 6; 10)
return $htOutput
} catch {
Write-Host "Error: $($_.Exception)" -ForegroundColor White -BackgroundColor Red
break
}
}
End {
if ($?) {
Write-Host "SO Question End..." -ForegroundColor Black -BackgroundColor Green
}
}
}
& $main
预期输出为:
$htOutput = @{Alpha = 0; Bravo = 1; Charlie = 3; Delta = 6; Echo = 10}
但实际输出是:
$htOutput = @(0; 1; 3; 6; 10)
请指教?
答案 0 :(得分:3)
感觉就像做作业。但是,我看到你真诚的努力,我喜欢。您将结果定义为数组 - $htOutput = @()
,因为您已将结果定义为数组。您需要将其作为哈希表 - $htOutput = @{}
。
注意:最好初始化所有变量。需要注意的第二件事是,他通过.GetEnumerator
排序可能会受到您的区域设置的影响。这可能导致偏离你希望的结果。
$main = {
begin {
Write-Host "SO Question Begin..." -ForegroundColor Black -BackgroundColor Green
}
process {
try {
$htInput = @{Alpha = 1; Bravo = 2; Charlie = 3; Delta = 4; Echo = 5}
$htOutput = @{}
$temp = 0
$counter = 0
ForEach ($item in $htInput.GetEnumerator()) {
$temp = $temp + $counter
$htOutput.Add($item.key,$temp)
$counter++
}
# Expected Output: $htOutput = @{Alpha = 0; Bravo = 1; Charlie = 3; Delta = 6; Echo = 10}
# Actual Output : $htOutput = @(0; 1; 3; 6; 10)
return $htOutput
}
catch {
Write-Host "Error: $($_.Exception)" -ForegroundColor White -BackgroundColor Red
break
}
}
end {
If ($?) {
Write-Host "SO Question End..." -ForegroundColor Black -BackgroundColor Green
}
}
}
& $main