0

so my main goal is to be able to create multiple variations of an XML element (using powershell if possible). For example, the xml structure below:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

</note>

Question 1: Is there a way to save that entire structure in one variable?

Question 2: How would I "save" that structure and create multiple copies of that structure with only one modification such as changing the Jani to cody and John? I want to be able to make modified copies of that structure at will but don't know where to start.

Any help appreciated. Thank you!

0

1 Answer 1

1

Use a Here-String for that with placeholders.

$xmlTemplate = @"
<note>
    <to>{0}</to>
    <from>{1}</from>
    <heading>{2}</heading>
    <body>{3}</body>
</note>
"@

Then use that to create as many of these xml fragments as you like. The placeholders {0}, {1} etc. get their true values using the -f Format operator like:

# this demo uses an array of Hashtables
$messages = @{To = 'Tove'  ; From = 'Jani'; Heading = 'Reminder'    ; Body = "Don't forget me this weekend!"},
            @{To = 'Bloggs'; From = 'Cody'; Heading = 'Cancellation'; Body = "No can do!"},
            @{To = 'Doe'   ; From = 'John'; Heading = 'Information' ; Body = "How about next weekend?"}

$messages.GetEnumerator() | ForEach-Object {
    $xmlTemplate -f $_.To, $_.From, $_.Heading, $_.Body 
}

Result:

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
<note>
    <to>Bloggs</to>
    <from>Cody</from>
    <heading>Cancellation</heading>
    <body>No can do!</body>
</note>
<note>
    <to>Doe</to>
    <from>John</from>
    <heading>Information</heading>
    <body>How about next weekend?</body>
</note>
Sign up to request clarification or add additional context in comments.

4 Comments

Neat! Quick (hopefully) question: what would be the simplest way to save all these fragments to one combined xml file?
@JackFleeting. Caprure the result as in $result = $messages.GetEnumerator(), enclose that inside a root element and save as .xml
You're right, but I think you meant to address the comment to OP, not to me... I already upvoted the answer.
@JackFleeting Ah, sorry about that. I was too lazy to scroll up and check the OP's name.. Thanks for the upvote BTW ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.