Reputation: 77
I made a PowerShell script to read and write infos/settings to an .xml file.
Param(
[string]$mode,
[string]$set,
[string]$xml
)
function readSettings([string]$xmlfile, [string]$setting)
{
$s = readSettings $xmlfile
$v = $s[$setting]
Write-Host $v
}
function exportSettings([string]$xmlfile)
{
$xmlDoc = New-Object XML
$xmlDoc.Load($xmlfile)
$settings = @{}
$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
return $settings
}
function importSettings([hashtable]$ht,[string]$xmlFile){
$xmlDoc = New-Object XML
$xmlDoc.Load($xmlFile)
foreach ($key in $ht.keys){
$settingNode = $xmlDoc.SelectSingleNode("/settings/setting[@name='$key']")
if ($settingNode){
$settingNode.firstChild.Value = $ht[$key]
}else{
$newNode = $xmlDoc.settings.setting[0].Clone()
$newNode.name = $key
$newNode.firstChild.Value = $ht[$key]
$xmlDoc.settings.appendChild($newNode)
}
}
$xmlDoc.Save($xmlFile)
}
if($mode -eq "read")
{
readSettings($xml, $set)
}
if ($mode -eq "write")
{
}
(Also on GitHub.)
Whenever I read an .xml file, it generates an endless loop with RAM consumption up to 2GB.
I thought that
$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
could be the reason, but I don't know how to solve it. Writing to a xml-file works perfectly fine. Can anyone help?
Upvotes: 1
Views: 136
Reputation: 77
i'm retared... i called the wrong function...
it should be $s = exportSettings $xmlfile
sorry guys for wasting your time :)
one problem less...
thanks you guys!
if you need:
function xml_readSettings([string]$xmlfile, [string]$setting)
{
$xmlDoc = New-Object XML
$xmlDoc.Load($xmlfile)
$settings = @{}
$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
return $settings[$setting]
}
function xml_exportHashtable([string]$xmlfile)
{
$xmlDoc = New-Object XML
$xmlDoc.Load($xmlfile)
$settings = @{}
$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
return $settings
}
function xml_writeSettings([hashtable]$ht, [string]$xmlfile)
{
$xmlDoc = New-Object XML
$xmlDoc.Load($xmlFile)
foreach ($key in $ht.keys){
$settingNode = $xmlDoc.SelectSingleNode("/settings/setting[@name='$key']")
if ($settingNode){
$settingNode.firstChild.Value = $ht[$key]
}else{
$newNode = $xmlDoc.settings.setting[0].Clone()
$newNode.name = $key
$newNode.firstChild.Value = $ht[$key]
$xmlDoc.settings.appendChild($newNode)
}
}
$xmlDoc.Save($xmlFile)
}
its now working :)
Upvotes: 0
Reputation: 72610
I think that readSettings
function call itself without test, and that's enough to loop I think.
function readSettings([string]$xmlfile, [string]$setting)
{
$s = readSettings $xmlfile
$v = $s[$setting]
Write-Host $v
}
Upvotes: 2