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

如何在PowerShell中创建可迭代字典/表并进行遍历?

在PowerShell中创建可迭代的子网配置表并遍历

在PowerShell中,你需要的是包含自定义属性的对象数组(而非传统键值对字典),这样就能通过$item.subnet和$item.address的方式访问每个项的属性,以下是两种常用实现方式:

方式一:直接创建自定义对象数组

这种方式直观易懂,适合少量固定数据的场景:

# 创建包含子网信息的自定义对象数组
$dictionary = @(
    [PSCustomObject]@{
        subnet  = 'xyz'
        address = '10.1.2.0/24'
    },
    [PSCustomObject]@{
        subnet  = 'abc'
        address = '10.1.3.0/24'
    },
    [PSCustomObject]@{
        subnet  = 'psh'
        address = '10.1.4.0/24'
    }
)

方式二:通过CSV格式转换

如果需要管理大量子网数据,或者数据来自外部文件,用CSV格式会更便捷:

# 定义CSV格式的子网数据
$subnetData = @"
subnet,address
xyz,10.1.2.0/24
abc,10.1.3.0/24
psh,10.1.4.0/24
"@

# 将CSV转换为可迭代的对象数组
$dictionary = $subnetData | ConvertFrom-Csv

遍历数组创建子网配置

注意:你原代码中每次循环会覆盖$dmz变量,建议将生成的子网配置存入数组,方便后续统一使用:

# 初始化空数组存储子网配置
$subnetConfigs = @()

foreach ($item in $dictionary) {
    $subnetConfig = New-AzVirtualNetworkSubnetConfig -Name $item.subnet -AddressPrefix $item.address
    $subnetConfigs += $subnetConfig
}

# 后续可将$subnetConfigs用于创建虚拟网络
# $vnet = New-AzVirtualNetwork -ResourceGroupName "你的资源组名" -Name "虚拟网络名" -AddressPrefix "10.1.0.0/16" -Subnet $subnetConfigs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:33:57