ashish g
ashish g

Reputation: 291

Powershell using Regex finding a string within a string in XML

I have an xml file and I need to read only a particular substring from the main string. The xml file looks like below:

<?xml version="1.0" encoding="utf-8"?>
<Report Version="10.0">
<Entities>
<Entity Name="\\sharing\Data\SB\**appname**\wcf\Utilitysvc\bin\svcUtility.Host.dll">
<Mods>
<Mod Name="svcUtility.Host.dll" AssemblyVersion="1.0.2000.001">
<Fields>
<Field Name="TIndex" Value="100" />            
<Field Name="Vindex" Value="200" />
</Fields>
</Mod>
</Mods>
</Entity>
</Entities>
</Report>

The main string in this xml is -

<Entity Name="\\sharing\Data\SB\**appname**\wcf\Utilitysvc\bin\svcUtility.Host.dll">

And I need to print only the "appname" from it.

What condition logic can I use to print this using regex in powershell? And it need not be \wcf after the appname always.. it can be anything based on the dll path. For Eg, it can be like:

<Entity Name="\\sharing\Data\*SB*\**appname**\**Web**\Utilitysvc\bin\svcUtility.Host.dll">

or

<Entity Name="\\sharing\Data\*SB*\*DEVCS*\**appname**\**junk**\Utilitysvc\bin\svcUtility.Host.dll">

Can I have a generic select -string way? need to test this as well..

Thanks,
Ashish

Upvotes: 1

Views: 3898

Answers (2)

CB.
CB.

Reputation: 60938

This is a way:

$xml = [xml](get-content .\my.xlm )

 ($xml.Report.Entities.Entity.name | 
% { [regex]::matches($_, 'SB\\(.*)\\wcf') } |
 select -expand groups)[1].value

without [regex] .net method:

($xml.Report.Entities.Entity.name |
select-string 'SB\\(.*)\\wcf' -AllMatches | select -ExpandProperty matches |
select -ExpandProperty groups)[1].value

Edit:

try this pattern based on your last comment:

 ($xml.Report.Entities.Entity.name |
    select-string '(?<=\\Data\\.*\\)[^\\]*' -AllMatches |
    select -ExpandProperty matches |
    select -ExpandProperty groups)[0].value

Upvotes: 2

Shay Levy
Shay Levy

Reputation: 126842

You can do that without the complexity of a regex, split the path and grab the 5th element (sounds like a movie name):

[xml]$xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Report Version="10.0">
<Entities>
<Entity Name="\\sharing\Data\SB\**appname**\wcf\Utilitysvc\bin\svcUtility.Host.dll">
<Mods>
<Mod Name="svcUtility.Host.dll" AssemblyVersion="1.0.2000.001">
<Fields>
<Field Name="TIndex" Value="100" />            
<Field Name="Vindex" Value="200" />
</Fields>
</Mod>
</Mods>
</Entity>
</Entities>
</Report>
"@

$xml.Report.Entities.Entity.Name.split('\')[5]

**appname**

Upvotes: 1

Related Questions