Reputation: 1549
I'm struggling with reading XML file with PowerShell.
The main idea is - I have a flag, that indicates whether to read or write config file. If it is needed to write file - the script gets paramters and save them to an XML file. If the flag is set to 'read' - PowerShell scripts takes no parameters, though it should get them from the saved XML.
The problem is reading from XML. I write to XML using the code:
$Config = @{}
$Config.parameter1 = $parameterValue
$Config.dictionaryWithArray = $dictWithArray
($Config | ConvertTo-XML).Save("$path")
The saved XML file result is:
<?xml version="1.0"?>
<Objects>
<Object Type="System.Collections.Hashtable">
<Property Name="Key" Type="System.String">parameter1</Property>
<Property Name="Value" Type="System.String">value_in_variable_parameter_Value</Property>
<Property Name="Key" Type="System.String">dictionaryWithArray</Property>
<Property Name="Value" Type="System.Collections.Generic.Dictionary`2[System.String,System.String[]]">
<Property Name="Key" Type="System.String">key1</Property>
<Property Name="Value" Type="System.String[]">
<Property Type="System.String">subkey1</Property>
<Property Type="System.String">subvalue1</Property>
</Property>
<Property Name="Key" Type="System.String">key2</Property>
<Property Name="Value" Type="System.String[]">
<Property Type="System.String">subkey2</Property>
<Property Type="System.String">subvalue2</Property>
</Property>
... and so on
I tried to read this config using methods such as http://blogs.technet.com/b/heyscriptingguy/archive/2012/09/13/powertip-use-powershell-to-easily-read-an-xml-document.aspx , but no luck.
Can you, please, tell how it is possible to read the config file, written by such method? Or may be there is the better way to serialize config before writing, so it would be easier to read it?
Upvotes: 2
Views: 5974
Reputation: 46730
There are ways to do this with XML but most of the blogs you might have read don't go into reading custom / nested objects from XML. I don't personally know of a way to do that though however I'm sure solutions exist.
Or may be there is the better way to serialize config before writing
That is what I want to focus on for my answer. You can use Export-CliXml
and its counterpart Import-CliXml
. Those cmdlets should do the work for you much easier.
#.... your other code that generates $config
$Config | Export-Clixml $path
Then you can just call the config back as required and check values like you would before you wrote the data to file.
$fileConfig = Import-Clixml $path
$fileConfig.parameter1
Be wary of how complex your objects get as you might need to use -Depth
of Export-CliXml
.
-Depth
Specifies how many levels of contained objects are included in the XML representation. The default value is 2.
Upvotes: 5