我制作了一个PowerShell脚本以将信息/设置读取和写入.xml文件。
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")
{
}
(也在GitHub上。)
每当我读取.xml文件时,它都会生成一个无限循环,其RAM消耗高达2GB。
我以为
$xmlDoc.settings.ChildNodes | %{$settings[$_.name] = $_.firstChild.Value}
可能是原因,但我不知道如何解决。写入xml文件非常正常。有人可以帮忙吗?
答案 0 :(得分:2)
我认为readSettings
函数本身无需测试即可调用,这足以循环我想。
function readSettings([string]$xmlfile, [string]$setting)
{
$s = readSettings $xmlfile
$v = $s[$setting]
Write-Host $v
}
答案 1 :(得分:0)
我被推迟了... 我叫错了功能...
应为 $s = exportSettings $xmlfile
对不起,浪费您的时间:)
少一个问题...
谢谢你们!
如果需要:
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)
}
它现在可以工作了:)