试图通过XML变量功能来更新XML文件

问题描述:

嗨,大家好(也许加仑),试图通过XML变量功能来更新XML文件

在PowerShell中我想要一个变量传递给我的功能,我想用来更新特定节点在我的XML文件中。我想将变量$ xml.config.server.username(我的XML文件中的节点)传递给我的函数,并使用它来检查它是否已填充,如果未填充,请使用也传递给函数的$ Value填充它。

到目前为止,我尝试这样做:

function XMLChecker 
(
    [Parameter(Mandatory=$true)] $XMLFile, 
    [Parameter(Mandatory=$true)] $Value, 
    [Parameter(Mandatory=$true)] $LocationinXML 
) 

{ 
$XML = New-Object XML 
$XML.load($XMLFile) 

if ($LocationinXML -eq "") { 
     Write-host "Value $Value is not found in XML file, adding it in the file." -fore Yellow 
     $LocationinXML = [string]$Value 
     $XML.save("$XMLFile") 
     $XML.load("$XMLFile") 
    } 

,并调用函数,我试过这样:

XMLChecker -XMLFile C:\config.xml -Value "jabadabadoo" -LocationinXML "$xml.config.server.username" -ErrorAction Stop 

这是我测试的XML文件的一部分:

<config version="1.0"> 
    <server dnsname="localhost" ip="127.0.0.1" username="share" /> 
</config> 

我猜这是我忽略的小事情(对你们来说很简单:))。

+0

'如果($ LocationinXML -eq “”)'是自相矛盾。这不会起作用。 –

您可以使用scriptblock参数或Invoke-Expression +字符串参数来实现此目的。我会避免在参数值中需要$xml,因为用户不必知道该函数是如何构建的。

调用-表达:

function XMLChecker { 
    param(
     [Parameter(Mandatory=$true)] $XMLFile, 
     [Parameter(Mandatory=$true)] $Value, 
     [Parameter(Mandatory=$true)] $LocationinXML 
    ) 

    $XML = New-Object XML 
    $XML.load($XMLFile) 

    if ((Invoke-Expression "`$xml.$LocationinXML") -eq "") { 
     Write-host "Value $Value is not found in XML file, adding it in the file." -fore Yellow 
     Invoke-Expression "`$xml.$LocationinXML = '$Value'" 
     $XML.save("$XMLFile") 
    } 

} 

XMLChecker -XMLFile "C:\config.xml" -Value "jabadabadoo" -LocationinXML "config.server.usernames" -ErrorAction Stop 

脚本块:

function XMLChecker { 
    param(
     [Parameter(Mandatory=$true)] $XMLFile, 
     [Parameter(Mandatory=$true)] $Value, 
     [Parameter(Mandatory=$true)] [scriptblock]$LocationinXML 
    ) 

    $XML = New-Object XML 
    $XML.load($XMLFile) 

    if (($LocationinXML.Invoke().Trim()) -eq "") { 
     Write-host "Value $Value is not found in XML file, adding it in the file." -fore Yellow 
     [scriptblock]::Create("$LocationinXML = '$Value'").Invoke()   
     $XML.save("$XMLFile") 
    } 

} 

XMLChecker -XMLFile "C:\config.xml" -Value "jabadabadoo" -LocationinXML { $xml.config.server.username } -ErrorAction Stop 
+0

充当魅力。感谢您的回应和选项! – MMast