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

如何处理PowerShell Add-Content输出?消除CSV中的@{Datum=类冗余内容

PowerShell脚本输出CSV冗余内容修复方案

问题原因

你遇到的@{Datum=...这类冗余内容,根源是使用了Add-Content命令——它会将PowerShell对象直接转为默认字符串格式输出,而非正确序列化CSV结构。

需要修改的核心部分

直接替换脚本最后一行的Add-Content为Export-Csv,并补充必要参数:

  • 用-Path指定输出路径
  • 添加-Append实现追加写入(若文件已存在,保留原有内容)
  • 加上-NoTypeInformation避免CSV首行写入PowerShell对象类型信息
  • 可选-Encoding UTF8确保特殊字符或中文显示正常

修改后的完整代码

$Report = @( )
$Datum = Get-Date -Format "dd.MM.yy"
$Zeit = Get-Date -Format "HH:mm:ss"
$Computers = "computer1","computer2"

foreach ($Computer in $Computers) {
    if (Test-Connection $Computer -Count 1 -Quiet) {
        $TestResult = [PSCustomObject]@{
            Datum    = $Datum
            Zeit     = $Zeit
            Computer = $Computer
            Result   = "Online"
        }
    }
    else {
        $TestResult = [PSCustomObject]@{
            Datum    = $Datum
            Zeit     = $Zeit
            Computer = $Computer
            Result   = "Offline"
        }
    }
    $Report += $TestResult
}       

# 替换原Add-Content为Export-Csv
$Report | Select-Object Datum, Zeit, Computer, Result | 
    Export-Csv -Path "C:\kr\powershell\serverstatus4.csv" -Append -NoTypeInformation -Encoding UTF8

额外优化提示

  • 用[PSCustomObject]替代New-Object psobject -Property,语法更简洁且性能更优
  • 若不需要提前收集所有结果到$Report数组,可直接在循环内将$TestResult输出到Export-Csv -Append,减少内存占用

内容的提问来源于stack exchange,提问作者spicehead-n570c

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:50:49