ashish g
ashish g

Reputation: 291

How can I remove substring from the main string using Powershell script?

My powershell code actually reads data from an XML and stores the specific data to a csv file. The XML file somewhat looks like below:

<?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>

I need to extract only the "testing.dll" from the above XML code. The code I am using to do so is as below:

$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'  

I don't need AssemblyVersion to be concatenated to the "testing.dll (mod name in xml)" from the XML code.

Currently I get something like:

 testing.dll" AssemblyVersion=1.0.1000.112" 

I just need testing.dll, everything thereafter should be ommitted.

Please help.

Thanks, Ashish

Upvotes: 1

Views: 365

Answers (2)

Emiliano Poggi
Emiliano Poggi

Reputation: 24816

Use XML as correctly suggested by JPBlanc. Then use XPath. Example, to extract the wanted value:

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

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72610

I don't think that regular expression is the best way to parse XML. Perhaps ou'd better use XMLDocument.

Using a better XML document :

<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>

You can find your data like this :

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

Upvotes: 3

Related Questions