【问题标题】:How can I remove substring from the main string using Powershell script?如何使用 Powershell 脚本从主字符串中删除子字符串?
【发布时间】:2012-10-10 17:55:25
【问题描述】:

我的 powershell 代码实际上是从 XML 读取数据并将特定数据存储到 csv 文件中。 XML 文件 如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Report Version="10.0">
<Targets>
<Target Name="\\bin\testBusiness.dll">
<Modules>
<Module Name="testing.dll" AssemblyVersion="1.0.1003.312" FileVersion="1.0.0.0">
<Metrics>
<Metric Name="Maintainability" Value="78" />
</Metrics>
</Module>
</Modules>
</Target>
</Targets>
</Report>

我需要仅从上述 XML 代码中提取“testing.dll”。我用来这样做的代码如下:

$testDLL = [regex]::matches($xmlfile[5], '<mod name=".*" ')[0].value -replace '<mod name="(.*)" ','$1'
#the above code line gets even the AssemblyVersion 
$testAssembver =  [regex]::matches($xmlfile[5], 'AssemblyVersion=".*" ')[0].value -replace 'AssemblyVersion=".*" ','$1'  

我不需要将 AssemblyVersion 连接到 XML 代码中的“testing.dll(xml 中的模块名称)”。

目前我得到类似的东西:

 testing.dll" AssemblyVersion=1.0.1000.112" 

我只需要 testing.dll,之后的所有内容都应该省略。

请帮忙。

谢谢, 灰烬

【问题讨论】:

    标签: powershell replace substring


    【解决方案1】:

    我不认为正则表达式是解析 XML 的最佳方式。也许你最好使用 XMLDocument。

    使用更好的 XML 文档:

    <Dumy>
    <Report Version="10.0"></Report>
    <Goals>
      <Name>"\\somepath\path.dll"</Name>
      <Mods>
        <Mod Name="testing.dll" AssemblyVersion="1.0.1000.112" FileVersion="1.0.0.1"></Mod>
      </Mods>
    </Goals>
    </Dumy>
    

    你可以像这样找到你的数据:

    $data = [XML](Get-Content "C:\temp\test.xml")
    $data.Dumy.Goals.Mods.Mod.Name
    

    【讨论】:

    • 感谢您为 JPBlanc 所做的努力。但是有没有办法使用 -replace 两次或其他方法。我得到了 testing.dll,但还有我需要省略的 AsemblyVersion。
    • 当我使用您的代码时,我实际上将该字段设为空白。 :(
    • 你能从你的 XML 代码中提取一个连贯的部分吗(格式正确)?
    • @hashish,JPBlanc 使用了您的 XML 的修改版本。您是否根据您的情况调整了代码?
    【解决方案2】:

    按照 JPBlanc 的正确建议使用 XML。然后使用 XPath。例如,提取想要的值:

    $data.selectnodes("//Modules/Module/@Name")
    

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多