Matt
Matt

Reputation: 379

Find and replace in XML file with powershell

Right now I am generating an XML file with a GUI using PowerShell Studio 2017. This snippet of code gathers the checked items inside a CheckedListBox:

$Groups = $chklistGroups.CheckedItems | ForEach-Object {
    "<Group>$_</Group>`n`t`t`t`t"
}

Some of these checkboxes contain &, which obviously cannot be inside of an XML file. Is there any way of removing the & and replacing it with the appropriate &amp; within this snippet of code? This XML file is then passed into a different script, where I attempted to remove the ampersands' with this:

# check the xml file for & and replace them with &amp; so it doesn't crash - except it doesn't work so it's gonna crash
if ($NewUserXML.NewUser.ActiveDirectory.User.Groups.Group.Contains("&"))
{
    "$($NewUserXML.NewUser.ActiveDirectory.User.Groups.Group)".Replace('&','&amp;')
}

Is it generally better to do this before the XML is created, or after it's put into the script itself? My assumption is that it's better to do it before it's created. If so, is it possible to do it in that first snippet of code?

Upvotes: 1

Views: 462

Answers (1)

G42
G42

Reputation: 10019

You could complete the replace within your ForEach-Object:

$Groups = $chklistGroups.CheckedItems | ForEach-Object {
    "<Group>$($_.Replace('&','&amp;'))</Group>`n`t`t`t`t"
}

Upvotes: 2

Related Questions