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

PowerShell如何将TXT结构化内容转换为内存自定义对象数组

PowerShell分块读取TXT生成自定义对象数组实现方案

核心逻辑思路

  • 采用状态机模式遍历文件行,维护两个核心变量:当前正在拼接的临时块对象$currentItem、存储最终结果的对象数组$result
  • 识别块边界:常规结构化分块TXT的块间隔为空行/固定起始字段,检测到新块启动时,先将已拼接完成的上一个临时对象存入结果数组,再初始化新的临时对象
  • 遍历结束后单独将最后一个块存入结果数组,避免因最后一块后无分隔符导致的数据丢失

完整可运行代码示例

# 初始化结果集合和临时块对象
$result = [System.Collections.Generic.List[PSObject]]::new()
$currentItem = $null

# 逐行读取目标TXT文件
Get-Content -Path "替换为你的TXT文件路径" | ForEach-Object {
    $line = $_.Trim()
    # 空行判定为块分隔符,可根据实际分隔规则修改
    if ([string]::IsNullOrEmpty($line)) {
        if ($null -ne $currentItem) {
            $result.Add($currentItem)
            $currentItem = $null
        }
        return
    }

    # 拆分键值对,默认分隔符为冒号,可根据实际规则调整
    $keyValue = $line -split ':', 2 | ForEach-Object { $_.Trim() }
    $key = $keyValue[0]
    $value = $keyValue[1]

    # 检测到块起始标记(Object GUID为块首字段)时初始化新对象
    if ($key -eq 'Object GUID' -and $null -eq $currentItem) {
        $currentItem = [PSCustomObject]@{
            'Object GUID' = $null
            'Name' = $null
            'Location' = $null
            'Threat name' = $null
            # 可根据需求新增其他属性
        }
    }

    # 匹配属性赋值,非目标字段自动忽略
    if ($null -ne $currentItem -and $currentItem.PSObject.Properties.Name -contains $key) {
        $currentItem.$key = $value
    }
}

# 补入最后一个没有尾部分隔符的块
if ($null -ne $currentItem) {
    $result.Add($currentItem)
}

# 输出验证,$result即为可直接调用的自定义对象数组
# $result | Format-Table

适配调整说明

  • 若块分隔符不是空行,将空行判定逻辑替换为对应分隔符匹配逻辑即可
  • 若键值对分隔符不是冒号,修改-split ':'中的分隔符即可
  • 不需要的属性可直接在初始化$currentItem的代码段中删除对应字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:27:03