2016-04-30 66 views
1

嗨,大家好(也許加侖),試圖通過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 「」)'是自相矛盾。這不會起作用。 –

回答

1

您可以使用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