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

如何在PowerShell中将关联变量对象分多行输出?

解决PowerShell中关联数组的多行输出问题

你的代码存在两个核心问题:

  1. 变量名不匹配:定义的数组是$Identification,但输出时用了未定义的$ID
  2. 直接输出数组会将所有元素拼接在一行,无法实现按索引关联的多行输出

以下是几种可行的解决方案:

方法1:使用For循环遍历索引(兼容所有PowerShell版本)

通过索引逐个获取两个数组中对应的元素,然后逐行输出:

$Identification = 123, 234, 543, 213
$Num = 8999, 2342, 1238, 9993

for ($i = 0; $i -lt $Identification.Count; $i++) {
    Write-Host "The ID is $($Identification[$i]), and the Num is $($Num[$i])."
}

方法2:使用Zip命令(PowerShell 7及以上版本)

PowerShell 7引入了Zip运算符,可以直接将两个数组按索引配对,简化遍历逻辑:

$Identification = 123, 234, 543, 213
$Num = 8999, 2342, 1238, 9993

foreach ($pair in $Identification | Zip $Num) {
    Write-Host "The ID is $($pair[0]), and the Num is $($pair[1])."
}

方法3:组合为自定义对象(适合需后续处理数据的场景)

将关联的ID和Num封装为自定义对象,既可以实现多行输出,也方便后续对数据进行过滤、排序等操作:

$Identification = 123, 234, 543, 213
$Num = 8999, 2342, 1238, 9993

# 生成包含关联数据的自定义对象数组
$combinedData = for ($i = 0; $i -lt $Identification.Count; $i++) {
    [PSCustomObject]@{
        ID  = $Identification[$i]
        Num = $Num[$i]
    }
}

# 逐行输出对象内容
$combinedData | ForEach-Object {
    Write-Host "The ID is $($_.ID), and the Num is $($_.Num)."
}

以上三种方法都能输出你需要的格式:

The ID is 123, and the Num is 8999.
The ID is 234, and the Num is 2342.
The ID is 543, and the Num is 1238.
The ID is 213, and the Num is 9993.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 02:20:06