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

PowerShell使用Export-Csv导出PSCustomObject为CSV失败求助

PowerShell Export-Csv 生成CSV失败问题解决

问题场景

原本使用以下PowerShell代码,通过Out-File生成包含键值对的文件:

$result = @()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
if ($_.ReplacementStrings[5] -ne "SYSTEM")
   {
       $result += [PSCustomObject]@{
           Time = $_.TimeGenerated
           Workstation = $_.ReplacementStrings[11]
       }
   }
 }
#$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
$result | Out-File "C:\\Temp\\Logins.csv"

之后需要生成标准CSV格式,将代码改为使用Export-Csv:

$result = @()
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
 ForEach-Object {
   if ($_.ReplacementStrings[5] -ne "SYSTEM")
   {
       $result += [PSCustomObject]@{
           Time = $_.TimeGenerated
           Workstation = $_.ReplacementStrings[11]
       }
   }
 }
$result | Export-Csv -Path .\Logins.csv -NoTypeInformation
#$result | Out-File "C:\\Temp\\Logins.csv"

但修改后生成的结果不符合预期,无法得到正确的CSV格式。

问题原因与解决方法

  • 数组拼接的潜在问题:使用$result += [PSCustomObject]会频繁创建新数组,不仅效率低下,还可能导致对象类型出现隐性异常,干扰Export-Csv的正常解析。
  • 优化管道传递逻辑:无需预先初始化空数组,直接通过管道将PSCustomObject输出给Export-Csv,能避免数组操作带来的类型问题,同时提升代码效率。

改进后的代码:

Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
    if ($_.ReplacementStrings[5] -ne "SYSTEM") {
        [PSCustomObject]@{
            Time = $_.TimeGenerated
            Workstation = $_.ReplacementStrings[11]
        }
    }
} | Export-Csv -Path .\Logins.csv -NoTypeInformation -Encoding UTF8

额外说明

  • 添加-Encoding UTF8参数可避免中文或特殊字符乱码;
  • 若仍有异常,可先验证输出对象类型,确认是否为PSCustomObject:
Get-EventLog -LogName Security -After ((Get-Date).AddDays(-5)) -InstanceId 4624 |
ForEach-Object {
    if ($_.ReplacementStrings[5] -ne "SYSTEM") {
        [PSCustomObject]@{
            Time = $_.TimeGenerated
            Workstation = $_.ReplacementStrings[11]
        }
    }
} | Get-Member

只要输出对象是PSCustomObject类型,Export-Csv就能正常生成标准CSV文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:57:19