如何使用powershell解析此xml?

时间:2016-12-23 21:12:01

标签: regex powershell xml-parsing

我需要一些正则表达式帮助来解析日志文件中的powershell对象。

想要使用这些音符属性制作一个powershell对象:

ACVS_D = Date
ACVS_TI = Info
ACVS_C = Name
ACVS_M = Message

任何帮助将不胜感激!谢谢!

.log文件中的xml示例:

<ACVS_T>
    <ACVS_D>12/23/2016 03:25:14.324</ACVS_D>
    <ACVS_TI>db818c30-cdb9-4482-9b51-8f6aad8e914c,C?Cure Reports Server Component,svc-ccureMAS</ACVS_TI>
    <ACVS_C>CrossFireWindowsService</ACVS_C>
    <ACVS_S>SoftwareHouse.CrossFire.Server.Shared.CrossFireWindowsService.TraceMessage( String methodName, String message )
</ACVS_S>
    <ACVS_M>
        CrossFireReportServer.ReconnectToServer() connected at 12/23/2016 3:25:14 AM
    </ACVS_M>
<ACVS_ST>

    </ACVS_ST>
</ACVS_T>
<ACVS_T>
    <ACVS_D>12/23/2016 03:25:14.324</ACVS_D>
    <ACVS_TI>6af6dfab-c890-42c5-acd2-a9520e9742da,C?Cure Reports Server Component,svc-ccureMAS</ACVS_TI>
    <ACVS_C>CrossFireWindowsService</ACVS_C>
    <ACVS_S>SoftwareHouse.CrossFire.Server.Shared.CrossFireWindowsService.TraceMessage( String methodName, String message )
</ACVS_S>
    <ACVS_M>
        CrossFireReportServer.ReconnectToServer() connected at 12/23/2016 3:25:14 AM
    </ACVS_M>
<ACVS_ST>

    </ACVS_ST>
</ACVS_T>

1 个答案:

答案 0 :(得分:0)

我不建议使用正则表达式,除非它是非常大的文件。 您需要一个像此(?<=<ACVS_T>)((.|\n)*)(?=<\/ACVS_T>)这样的正则表达式搜索字符串 请根据您需要调整每个部分。

您只需添加根节点并将其解释为XML文件即可。 如下例所示:

$File = "PathToFile"

$XML =  [XML]("<Root>" + (Get-Content -Path $File) + "</Root>" )

$XML.Root.ACVS_T | ForEach-Object {
    $Obj = '' | Select-Object -Property ACVS_D, ACVS_TI, ACVS_C, ACVS_S, ACVS_M, ACVS_ST
   $Obj.ACVS_D = $_.ACVS_D
   $Obj.ACVS_ST = $_.ACVS_ST
   $Obj.ACVS_C = $_.ACVS_C
   $Obj.ACVS_S = $_.ACVS_S
   $Obj.ACVS_M = $_.ACVS_M
   $Obj.ACVS_ST = $_.ACVS_ST
   $Obj
}