Christopher Cass
Christopher Cass

Reputation: 969

Create Variable From Commented Out XML Values With PowerShell

I have a license file with a lot of commented out fields that I need to make into variables. The different lines may or may not exist, so I need to find out if the line exists, and if it does, turn it into a variable. I have file.xml formatted as:

<?xml version="1.0" encoding="utf-8"?>
<License>
    <!--MAC address XXXXXXXXXXXXXXX-->
    <!--NodeID "NODEID"-->
    <!--start date 4/27/2020 1:25:11 PM-->
    <!--expiry date 4/27/2119 1:25:11 PM-->
    <!--duration 99Years-->
    <!--Feature: Name=base-->
    <!--Feature: Name=free-->
    <!--Feature: Name=sharing-->
    <!--Feature: Name=3d-->
    <Content><![awholelotofmumobjump></Content>
</License>

I normally have no issue looking at XML files and creating variables, but I've never tried looking for anything that was commented out. So if I run:

[xml]$File = gc '\File.xml'

$File.License.'#comment'

I get back:

MAC address XXXXXXXXXXXXXXX
NodeID "NODEID"
start date 4/27/2020 1:25:11 PM
expiry date 4/27/2119 1:25:11 PM
duration 99Years
Feature: Name=base
Feature: Name=free
Feature: Name=sharing
Feature: Name=3d

So using the expiry date line, can anyone help me figure out how to see if that line exists and if so, turn it into a variable? From there, I know how to split it and get just the value, but I'm struggling to figure out this piece...

Upvotes: 1

Views: 39

Answers (1)

Don Cruickshank
Don Cruickshank

Reputation: 5948

This is not a great way to structure data in XML.

As it is, you'll have to resort to string manipulation functions to get the expiry date out. Having a general read through the about_operators document would probably be a worthwhile exercise.

Use -match to filter out the results you don't want and then -replace can be used to strip off the "expiry date" text from the start:

$ExpiryDateComment = $File.License."#comment" -match '^expiry date'

if ($ExpiryDateComment) {
    $ExpiryDate = $ExpiryDateComment -replace '^expiry date ', ''
    $ExpiryDate
}

Upvotes: 1

Related Questions