I have an XML file with several entries using same keys and values handling credentials with PowerShell, constructed by Explort-Clixml
. An example:
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
<Obj RefId="0">
<TN RefId="0">
<T>System.Collections.Hashtable</T>
<T>System.Object</T>
</TN>
<DCT>
<En>
<S N="Key">fabrikam</S>
<Obj N="Value" RefId="1">
<TN RefId="1">
<T>System.Management.Automation.PSCredential</T>
<T>System.Object</T>
</TN>
<Props>
<S N="UserName">admin@fabrikam.com</S>
<SS N="Password">01000000...</SS>
</Props>
</Obj>
</En>
<En>
<S N="Key">contoso</S>
<Obj N="Value" RefId="2">
<TNRef RefId="1" />
<Props>
<S N="UserName">admin@contoso.com</S>
<SS N="Password">01000000...</SS>
</Props>
</Obj>
</En>
<En>
<S N="Key">adatum</S>
<Obj N="Value" RefId="3">
<TNRef RefId="1" />
<Props>
<S N="UserName">admin@adatum.com</S>
<SS N="Password">01000000...</SS>
</Props>
</Obj>
</En>
</DCT>
</Obj>
</Objs>
The same Export-Clixml
handles adding new entries to the list (as hashtables), but I'm struggling when I'd have to modify entries I already have.
1) If I specify to delete an item named contoso
, what is the best way to seek, select and remove everything from that <En>
entirely?
$xml = [xml](Get-Content file.xml)
$xml.SelectNodes("//Objs/Obj/DCT/En")
... yields nothing at all, whereas
$xml.Objs.Obj.DCT.En.s
works perfect and returns the list of entries by their name. I would need to remove an entire <En>
element per given value for <S N="Key">...</S>
. Trying to catch the correct entry with
$xml.Objs.Obj.DCT.En.ChildNodes | ? { '#text' -contains 'contoso' }
returns nothing.
2) RefId
value in Obj
is an auto incremented number. If I remove contoso
between the other two entries, what would be the best way to seek and replace the value of RefId
in fabrikam
and adatum
so they're in order (1,2) again? A noteworthy point here is that only the first <En>
in the list has sub-elements for <TN RefId>
element, the others do not.