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

如何用PowerShell递归解析XML并导出为CSV?

递归解析XML文件并导出到CSV的解决方案

需求说明

  • 递归遍历指定文件夹中的所有XML文件
  • 解析每个XML文件(结构见下文)并将数据追加到同一个CSV文件中

示例XML结构

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Author>Microsoft Corporation</Author>
    <URI>\OneDrive Reporting Task-S-1-5-21-XXXXXXXXXX-XXXXXXX-683614252-544081760</URI>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <StartBoundary>2022-09-07T12:45:02</StartBoundary>
      <Enabled>true</Enabled>
      <Repetition>
        <Interval>P1D</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-21-XXXXXXXX-XXXXXXX-683614252-544081760</UserId>
      <RunLevel>LeastPrivilege</RunLevel>
      <LogonType>InteractiveToken</LogonType>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>true</RunOnlyIfNetworkAvailable>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
    <Priority>7</Priority>
    <RestartOnFailure>
      <Interval>PT30M</Interval>
      <Count>2</Count>
    </RestartOnFailure>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>%localappdata%\Microsoft\OneDrive\OneDriveStandaloneUpdater.exe</Command>
      <Arguments>/reporting</Arguments>
    </Exec>
  </Actions>
</Task>

已实现的单文件解析代码

$xmlFile = [xml](get-content "OneDrive Reporting Task-S-1-5-21-xxxxxxxx-xxxxxxxx-683614252-544134134")
$Date = $xmlFile.ChildNodes.RegistrationInfo.Date
$Author = $xmlFile.ChildNodes.RegistrationInfo.Author
$Description = $xmlFile.ChildNodes.RegistrationInfo.Description
$URI = $xmlFile.ChildNodes.RegistrationInfo.URI
$Principals = $xmlFile.ChildNodes.Principals.Principal.UserId
$LogonType = $xmlFile.ChildNodes.Principals.Principal.LogonType
$Enabled = $xmlFile.ChildNodes.Triggers.CalendarTrigger.Enabled
$Action = $xmlFile.ChildNodes.Actions.Exec.Command
$Arguments = $xmlFile.ChildNodes.Actions.Exec.Arguments

$xmlFile.ChildNodes[1] | 
ForEach-Object{
         [PSCustomObject]@{
             Registration_Date = $Date
             Author = $Author
             Description = $Description
             URI = $URI
             Principals_UserContext = $Principals
             LogonType = $LogonType
             Enabled = $Enabled
             Action = $Action
             Arguments = $Arguments
         }
     } | Export-Csv .\01Parsed_Tasks_XML.csv -NoTypeInformation

递归解析的完整解决方案

以下代码实现递归遍历、解析所有XML文件并追加数据到同一CSV:

# 配置路径:替换为你的目标文件夹和输出CSV路径
$rootFolder = "C:\Your\Target\Folder"
$outputCsv = ".\01Parsed_Tasks_XML.csv"

# 递归获取所有XML文件并逐个处理
Get-ChildItem -Path $rootFolder -Filter "*.xml" -Recurse -File | ForEach-Object {
    # 读取UTF-16编码的XML文件,避免乱码
    $xmlFile = [xml](Get-Content -Path $_.FullName -Encoding Unicode)
    
    # 提取注册信息
    $registrationInfo = $xmlFile.Task.RegistrationInfo
    $Date = $registrationInfo.Date
    $Author = $registrationInfo.Author
    $Description = $registrationInfo.Description
    $URI = $registrationInfo.URI
    
    # 提取主体信息
    $principal = $xmlFile.Task.Principals.Principal
    $Principals = $principal.UserId
    $LogonType = $principal.LogonType
    
    # 提取触发器启用状态(兼容TimeTrigger/CalendarTrigger等类型)
    $Enabled = $xmlFile.Task.Triggers.ChildNodes.Enabled
    
    # 提取执行动作信息
    $actionExec = $xmlFile.Task.Actions.Exec
    $Action = $actionExec.Command
    $Arguments = $actionExec.Arguments

    # 生成结构化数据(新增源文件路径便于排查)
    [PSCustomObject]@{
        Registration_Date       = $Date
        Author                  = $Author
        Description             = $Description
        URI                     = $URI
        Principals_UserContext  = $Principals
        LogonType               = $LogonType
        Enabled                 = $Enabled
        Action                  = $Action
        Arguments               = $Arguments
        Source_File             = $_.FullName
    }
} | Export-Csv -Path $outputCsv -NoTypeInformation -Append -Encoding UTF8

关键改进说明

  • 递归遍历:使用Get-ChildItem -Recurse自动遍历所有子文件夹中的XML文件
  • 编码兼容:指定-Encoding Unicode匹配XML的UTF-16编码,避免读取乱码
  • 节点访问优化:直接通过$xmlFile.Task访问根节点,比ChildNodes更直观可靠
  • 触发器兼容:通过ChildNodes获取触发器的启用状态,避免因触发器类型不同导致报错
  • 追加写入:使用-Append参数实现数据追加,首次运行自动创建CSV并写入表头
  • 溯源字段:新增Source_File字段记录数据来源的XML路径,便于后续验证和问题排查

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:35:23