将json作为powershell脚本中的参数传递

问题描述 投票:1回答:2

我已经创建了一个用于创建新的xml节点的函数。我的函数中有两个参数是现有的xml文件引用,第二个是元素值。运行脚本时显示错误

enter image description here

function createProviderNode($xmlData,$propertyValue){
Write-Host 'inside createProviderNode'
Write-Host ($propertyValue)
#[xml]$xmlData = get-content E:\powershell\data.xml
$newProviderNode = $xmlData.CreateNode("element","provider","")
$newProviderNode.SetAttribute("name",$propertyValue)
$xmlData.SelectSingleNode('providers').AppendChild($newProviderNode)
$xmlData.save("E:\powershell\data.xml")

}

我错过了这段代码吗?

powershell powershell-v2.0
2个回答
1
投票

错误消息暗示,虽然您希望$xmlData包含类型为[xml]System.Xml.XmlDocument)的对象 - 即XML文档 - 但实际上它是一个字符串([string])。

换句话说:当你调用createProviderNode函数时,你传递的第一个参数是一个字符串,而不是一个XML文档(类型为[xml)。

$xmlData参数变量键入为[xml]解决了这个问题,因为如果可能的话,它甚至会隐式地将字符串参数转换为XML文档。

一个简化的例子,使用脚本块代替函数:

$xmlString = @'
<?xml version="1.0"?><catalog><book id="bk101"><title>De Profundis</title></book></catalog>
'@

# Note how $xmlData is [xml]-typed.
& { param([xml] $xmlData) $xmlData.catalog.book.title } $xmlString

以上产生De Profundis,证明字符串参数已转换为[xml]实例(由于PowerShell的类型适应魔法 - 使元素名称可用作直接属性)。然后在.CreateNode()上调用$xmlData方法是安全的。


1
投票

好吧,您没有显示原始XML格式。你为什么评论Get-Content?没有它,它将无法运作。

因此,如果我们采用以下示例,它将按预期工作。

# Simple XML version

$SimpleXml = $null

$SimpleXml = @"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <name>Apple</name>
    <size>1234</size>
</configuration>
"@


# New node code
[xml]$XmlDoc = Get-Content -Path variable:\SimpleXml

$runtime = $XmlDoc.CreateNode("element","runtime","")

$generated = $XmlDoc.CreateNode("element","generatePublisherEvidence","")
$generated.SetAttribute("enabled","false")

$runtime.AppendChild($generated)

$XmlDoc.configuration.AppendChild($runtime)

$XmlDoc.save("$pwd\SimpleXml.xml")
Get-Content -Path "$pwd\SimpleXml.xml"


# Which creates this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <name>Apple</name>
  <size>1234</size>
  <runtime>
    <generatePublisherEvidence enabled="false" />
  </runtime>
</configuration>

除非您着色屏幕输出,否则永远不需要Write-Host。无论是否指定写入输出,写入输出都是默认值并自动写入屏幕。

所以,所有这些都是相同的 - 输出到屏幕。

$SomeString = 'hello'
Write-Host $SomeString
Write-Output $SomeString

'hello'
"hello"
$SomeString
"$SomeString"
($SomeString)
("$SomeString")
$($SomeString)

# Results

hello
hello
hello
hello
hello
hello
hello

......但是,这是你的选择。

© www.soinside.com 2019 - 2024. All rights reserved.