You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell循环中关联两个对应元素的数组?

PowerShell 对应数组元素循环输出方法

针对你需要将两个对应数组的元素配对输出的需求,这里提供几种简单易懂的实现方式:

方法一:基于索引的for循环(最直观)

这种方式通过数组索引来一一匹配元素,适合新手理解:

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

# 先检查两个数组长度是否一致,避免索引越界报错
if ($array1.Count -ne $array2.Count) {
    Write-Warning "两个数组长度不匹配,无法一一对应输出"
    exit
}

# 遍历索引,取对应位置的元素
for ($i = 0; $i -lt $array1.Count; $i++) {
    $serverName = $array1[$i]
    $sidValue = $array2[$i]
    Write-Host "Server=${serverName} and SID=${sidValue}"
}

方法二:使用ForEach-Object结合索引

通过遍历第一个数组,同时维护索引变量来获取第二个数组的对应元素:

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

if ($array1.Count -ne $array2.Count) {
    Write-Warning "两个数组长度不匹配"
    exit
}

$array1 | ForEach-Object -Begin { $index = 0 } -Process {
    # $_ 代表当前遍历的array1元素
    Write-Host "Server=${_} and SID=$($array2[$index])"
    $index++
}

方法三:使用.NET的Zip方法(更简洁)

利用.NET的Linq功能将两个数组直接配对,适合PowerShell 5.1及以上版本:

$array1 = @("server1", "server2")
$array2 = @("SID1", "SID2")

# 将两个数组对应元素配对,直接生成输出字符串
$pairedItems = [System.Linq.Enumerable]::Zip(
    $array1, 
    $array2, 
    [Func[string, string, string]]{ param($server, $sid) "Server=${server} and SID=${sid}" }
)

# 输出结果
$pairedItems | ForEach-Object { Write-Host $_ }

或者也可以直接在循环中处理配对后的元素:

[System.Linq.Enumerable]::Zip($array1, $array2) | ForEach-Object {
    Write-Host "Server=$($_.First) and SID=$($_.Second)"
}

内容的提问来源于stack exchange,提问作者lokicfb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:09:14