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

PowerShell中Invoke-RestMethod导出CSV拆分嵌套数组的实现

解决PowerShell嵌套订单对象转CSV时拆分明细行的问题

核心思路是通过两层循环遍历订单和其嵌套的SKU明细,将每个订单的公共字段(订单ID、参考编号等)与单个SKU的字段合并为独立对象,最终导出CSV即可实现一行对应一个SKU、公共字段自动重复的效果。

代码示例

先模拟API返回的订单数据结构(和你的实际返回结构对应即可):

# 模拟Invoke-RestMethod获取的订单数据
$orders = @(
    [PSCustomObject]@{
        OrderId = "ORD001"
        ReferenceNo = "REF001"
        CustomerName = "张三"
        Items = @(
            [PSCustomObject]@{Sku = "SKU001"; Quantity = 2; Price = 100},
            [PSCustomObject]@{Sku = "SKU002"; Quantity = 1; Price = 200}
        )
    },
    [PSCustomObject]@{
        OrderId = "ORD002"
        ReferenceNo = "REF002"
        CustomerName = "李四"
        Items = @(
            [PSCustomObject]@{Sku = "SKU003"; Quantity = 3; Price = 50}
        )
    }
)

处理逻辑及导出CSV:

$output = @()

foreach ($order in $orders) {
    # 处理空明细的情况,避免报错
    if (-not $order.Items -or $order.Items.Count -eq 0) {
        # 若订单无明细,也可生成一行空SKU的记录,根据需求调整
        $outputItem = [PSCustomObject]@{
            OrderId = $order.OrderId
            ReferenceNo = $order.ReferenceNo
            CustomerName = $order.CustomerName
            Sku = $null
            Quantity = $null
            Price = $null
        }
        $output += $outputItem
        continue
    }

    # 遍历每个SKU明细,合并公共字段与明细字段
    foreach ($item in $order.Items) {
        $outputItem = [PSCustomObject]@{
            OrderId = $order.OrderId
            ReferenceNo = $order.ReferenceNo
            CustomerName = $order.CustomerName
            Sku = $item.Sku
            Quantity = $item.Quantity
            Price = $item.Price
        }
        $output += $outputItem
    }
}

# 导出到CSV,指定编码避免乱码
$output | Export-Csv -Path "订单明细.csv" -NoTypeInformation -Encoding UTF8

关键说明

  • 两层循环是核心:外层遍历订单,内层遍历每个订单的SKU明细,每次循环生成包含订单公共字段和单个SKU字段的新对象,自然实现一行对应一个SKU。
  • 可根据实际订单结构,增减$outputItem中的字段,只要对应订单对象的非嵌套字段和明细对象的字段即可。
  • 加入了空明细的判断逻辑,可根据业务需求调整是否生成空明细行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:25:26