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

PowerShell将diskpart卷信息文本转CSV的空白值与导出错误处理问题

diskpart固定宽度输出转CSV的PowerShell正确实现

错误原因

  • 转换得到的[pscustomobject]对象没有被捕获就直接丢弃了,后续导出的是原始的OrderedDictionary字典对象,因此CSV里输出的是字典的属性而非磁盘数据
  • 导出和格式化输出逻辑写在foreach循环内部,会导致重复写入表头,且Format-Table输出的格式化对象不能用于后续CSV导出
  • 多余的$lines = $lines -split '\r?\n'操作,Get-Content默认已按行拆分返回数组

修正后的完整代码

$server = $env:COMPUTERNAME
# 读取磁盘信息文件
$lines = Get-Content "C:\d.txt"
# 拆分表头、分隔线、数据行
$header, $guardRails, $dataLines = $lines

# 提取列名
$columnNames = @(
  $header.Trim() -split '\s{2,}' | ForEach-Object Trim
)

# 提取每列的偏移量和长度
$columnOffsets = @(
  [regex]::Matches($guardRails, '(?<!-)-+(?!-)') | Select-Object Index, Length
)

# 收集所有解析结果
$result = foreach ($line in $dataLines) {
  $properties = [ordered]@{
    Server = $server
  }
  for ($i = 0; $i -lt $columnNames.Length; $i++) {
    $propName = $columnNames[$i]
    $offset = $columnOffsets[$i]
    $propValue = $line.Substring($offset.Index, $offset.Length).Trim()
    $properties[$propName] = $propValue
  }
  # 返回转换后的自定义对象,自动收集到$result数组
  [pscustomobject]$properties
}

# 控制台输出格式化结果
$result | Format-Table -AutoSize

# 统一导出到CSV,避免重复表头,指定UTF8编码防止乱码
$result | Export-Csv -Path "C:\$server.csv" -NoTypeInformation -Encoding UTF8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:45:03