我制作了一个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 文件工作得很好。谁能帮忙?
我认为readSettings
函数无需测试即可调用自己,我认为这足以循环。
function readSettings([string]$xmlfile, [string]$setting)
{
$s = readSettings $xmlfile
$v = $s[$setting]
Write-Host $v
}
我很迟钝...我调用了错误的函数...
应该是 $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)
}
它现在的工作:)