将输入哈希表中的键添加到输出哈希表

Adding Key From Input Hashtable To Output Hashtable

我想在输出哈希表 ($htOutput) 中使用输入哈希表 ($htInput) 中的键,而不知道具体的键名,只知道它们的数字位置。我可以使用 for 循环中的 $counter 变量访问各个输入哈希表键吗:

$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)

请指教?

感觉像是作业。但是,我看到你真诚的努力,我喜欢。您在 Array - $htOutput = @() 中得到结果,因为您已将结果定义为数组。您需要将其作为 Hash table - $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