【问题标题】:Very weird Powershell xml writing behaviour非常奇怪的 Powershell xml 写入行为
【发布时间】:2014-02-21 08:33:20
【问题描述】:

我正在开发一个将一些数据写入 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 专家,但这不是我所期望的。有什么想法我在这里做错了吗?
附言我最初的想法是我在 url 中搞砸了字符串插值。情况似乎并非如此 - 即使我删除了 http 部分,问题仍然存在。

【问题讨论】:

  • Get-Content -Path $storePath --> 什么是$storePath?它不是你的函数的参数,你从哪里得到它?
  • 是的,忘了提 - 这是函数内部定义的变量。编辑了问题

标签: xml powershell


【解决方案1】:

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

【讨论】:

  • 这就是我错过的。非常感谢。我只是需要更周到
猜你喜欢
  • 2016-03-13
  • 2011-03-01
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 2020-02-09
  • 1970-01-01
  • 2016-12-04
相关资源
最近更新 更多