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

PowerShell导出PSCustomObject至CSV异常问题求助

问题描述

本人是PowerShell新手,有VBA(主要用于Excel)使用经验。项目中需要将SQL查询返回的Instrument列数据与USB扫码枪输入的条码关联:循环读取每个Instrument对应的条码并存入集合,用Group-Object按Barcode分组后,通过[pscustomobject]生成符合预期的表格,终端显示正常,但使用Export-Csv导出时,CSV文件输出的是系统对象信息,而非终端展示的表格内容。

原代码如下:

foreach($inst in $values.Instrument) #loop through every Instrument result from SQL
{
    $temp = New-Object System.Object
    $temp | Add-Member -MemberType NoteProperty -Name "Barcode" -Value (Read-Host -Prompt "scan de barcode van: $($inst)")
    $temp | Add-Member -MemberType NoteProperty -Name "instrument" -Value $inst
    $instrument_data.Add($temp) | Out-Null
}
$groups = $instrument_data | Group-Object -property Barcode
foreach ($instrument in $groups) {
    [pscustomobject]@{'Barcode' = $instrument.Name; 'Instrument' = ($instrument.Group.Instrument | Foreach-Object { "$_" }) -join ','}
} 
$groups | export-csv -Path "export-path\file.csv" -NoTypeInformation
问题原因与解决办法

核心问题是你导出的是Group-Object返回的原始分组对象集合($groups),而非循环中生成的自定义格式化对象。终端显示的是循环输出的自定义对象,但你没把这些对象保存下来,反而导出了包含系统属性的分组对象,导致CSV内容不符合预期。

修正后的代码:

# 初始化存储扫码数据的集合(原代码遗漏,避免运行报错)
$instrument_data = New-Object System.Collections.ArrayList

foreach($inst in $values.Instrument) # 遍历SQL返回的每个Instrument
{
    $temp = New-Object System.Object
    $temp | Add-Member -MemberType NoteProperty -Name "Barcode" -Value (Read-Host -Prompt "扫描以下设备的条码: $($inst)")
    $temp | Add-Member -MemberType NoteProperty -Name "instrument" -Value $inst
    $instrument_data.Add($temp) | Out-Null
}

$groups = $instrument_data | Group-Object -property Barcode

# 存储格式化后的输出对象
$outputData = @()
foreach ($instrument in $groups) {
    $outputObj = [pscustomobject]@{
        'Barcode' = $instrument.Name; 
        'Instrument' = ($instrument.Group.Instrument -join ',') # 简化拼接写法,无需额外遍历
    }
    $outputData += $outputObj
    # 保留终端输出
    $outputObj
} 

# 导出格式化后的对象到CSV
$outputData | Export-Csv -Path "export-path\file.csv" -NoTypeInformation

额外优化说明:

  • 补充了$instrument_data集合的初始化,避免未定义变量报错
  • 简化了Instrument字段的拼接逻辑,直接用-join完成字符串合并
  • 新增$outputData变量存储所有自定义对象,确保导出内容与终端显示一致

内容的提问来源于stack exchange,提问作者Adriaan S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:20:42