首页 文章

Powershell在多个xml标记之间获取行

提问于
浏览
0

我目前正在尝试构建一个powershell脚本,它可以读取特定的XML文件并拉出某些单词 . 这些单词将位于标签之间 .

目前该文件看起来像这样 . 我们称之为events.xml:

<Computer>Hostname</Computer><Other>Random Text</Other<Other>More Random Text</Other><FilePath>notepad.exe</FilePath>

我想做的是,使用Powershell脚本在 <Computer></Computer><FilePath></FilePath> 标签之间提取单词并将它们回显给Powershell .

到目前为止我有这个:

gc events.xml | % { [regex]::matches( $_ , '(?<=<Computer>)(.*?)(?=</Computer>)' ) } | select -expa value

这在某种程度上起作用,因为它打印出 <Computer></Computer> 标签之间所有字符的列表完美无瑕 . 但是当尝试使脚本工作时,挑战就出现了,因此它将在BOTH( <Computer></Computer><FilePath></Filepath> )行之间打印出来 . 所以它会出现:

主机名
NOTEPAD.EXE

等等 .

有什么想法或建议吗?

谢谢!

2 回答

  • 0

    你应该尝试这样的事情:

    首先,使用以下命令加载XML目标文件:

    $xdoc = new-object System.Xml.XmlDocument
    $file = resolve-path(".\<name_file>.xml")
    $xdoc.load($file)
    $xdoc = [xml] (get-content ".\<name_file>.xml")
    

    /!\小心,你必须在好的目录中使用 .

    然后,如您所知,XML文档的结构,您应该尝试这样做:

    $Couples = $xdoc.[name_of_the_tag]
    

    选择 <Computers></Computers><FilePath></FilePath> 标记上方的标记 .

    然后,一个计数器,在while循环中使用它(开发你的xml):

    $CouplesCount = $Couples.Count
    

    在一个while循环中:

    $i = 0
    while($i -ne $CouplesCount ){
        $computer = $Couples.Computer
        $FilePath = $Couples.FilePath
    
        Write-Host $computer  
        Write-Host $FilePath 
        $i++
    }
    

    您应该使用 <Computers></Computers><FilePath></FilePath> 的值打印XML文件 .

  • 1

    感谢您通过XML解析向我指出正确的方向 .

    我通过这样做解决了我的脚本:

    $xdoc = new-object System.Xml.XmlDocument
    $file = resolve-path(".\events.xml")
    $xdoc.load($file)
    $xdoc = [xml] (get-content ".\events.xml")
    
    $xdoc.Events.Event |
    
    select @{ L = 'Computer';       E = { $_.System.Computer } },
           @{ L = 'FilePath';       E = { $_.UserData.RuleAndFileData.FilePath } }
    

    这导致了一个漂亮,干净的清单 .

    干杯!

相关问题