非常奇怪的Powershell xml写作行为

时间:2014-02-21 08:33:21

标签: xml powershell

我正在开发一个将一些数据写入XML文件的PS脚本。这是我使用的功能:

function addDeploymentRecord($serverPath, $typed, $branchName)
{
    $storePath = "C:\work\deployment\testing.xml"
    $document = [System.Xml.XmlDocument](Get-Content -Path $storePath)
    $record = $document.selectSingleNode("records").AppendChild($document.CreateElement("deployment"))

    $currentDate = Get-Date

    # Add a Attribute
    $record.SetAttribute("url", $serverPath)
    $record.SetAttribute("type", $typed)
    $record.SetAttribute("branch", $branchName)
    $record.SetAttribute("date", $currentDate)

    $document.Save($storePath)
}
我打电话是这样的:
addDeploymentRecord("http://localhost:${portNumber}/${applicationName}", "backend", $branchName)
我的xml文件包含一个空节点:<records></records>
运行脚本后,这是我添加到文件中的行:

<deployment url="http://localhost:90/task20118 backend task20118" type="" branch="" date="02/20/2014 19:16:13" />

这是否正常?我不是PowerShell大师,但那不是我的预期。我在这里做错了什么想法?
附: 我最初的想法是我在网址中搞砸了字符串插值。这似乎并非如此 - 即使我删除了http部分,问题仍然存在。

1 个答案:

答案 0 :(得分:4)

Powershell不使用括号来调用函数。

("http://localhost:${portNumber}/${applicationName}", "backend", $branchName)只是创建一个数组,然后调用该函数只将数组传递给$serverPath。当您替换变量时,数组的元素将使用空格连接。 你需要丢失括号和分隔参数的逗号:

PS D:\> function addDeploymentRecord($serverPath, $typed, $branchName)
{
    Write-Host "ServerPath is $serverPath"
    Write-Host "typed is $typed"
    Write-Host "branchName is $branchName"
}

PS D:\> $branchName = "myBranch"

PS D:\> addDeploymentRecord("http://localhost:${portNumber}/${applicationName}", "backend", $branchName)
ServerPath is http://localhost:/ backend myBranch
typed is 
branchName is 

PS D:\> addDeploymentRecord "http://localhost:${portNumber}/${applicationName}" "backend" $branchName
ServerPath is http://localhost:/
typed is backend
branchName is myBranch

或按名称传递参数:

PS D:\> addDeploymentRecord -serverPath "http://localhost:${portNumber}/${applicationName}" -typed "backend" -branchName $branchName
ServerPath is http://localhost:/
typed is backend
branchName is myBranch