【发布时间】:2017-09-17 12:26:38
【问题描述】:
当我从函数返回 XML 对象时,PowerShell 将其类型更改为 Object[]:
我在这里读到:
PowerShell changes return object's type
Preserving PowerShell function return type
https://www.experts-exchange.com/questions/27035513/How-to-stop-PowerShell-function-changing-return-type-of-ArrayList-or-string.html
如何防止它,他们都写道,在返回中添加逗号, 应该可以解决它。
我试过了:
return ,$computer
问题依然存在。
它仍然返回我 Object[] 类型而不是 XmlElement 类型。
示例代码:
Function getComputerXML($doc){
$computer = $doc.CreateNode("element","Computer",$null)
$computerSettings = $doc.CreateNode("element","ComputerSettings",$null)
$computerSettings.SetAttribute("Name","HP") | Out-Null
$computerSettings.InnerText = "someText"
$computer.AppendChild($computerSettings)
return $computer
}
Function main(){
[xml]$doc = New-Object System.Xml.XmlDocument
$computer = getComputerXML $doc
#$computers.AppendChild($computer)
}
main
【问题讨论】:
-
[void]$computer.AppendChild($computerSettings) -
@PetSerAl,它有效。你能解释一下为什么这个修复有效吗?
-
@E235 因为
AppendChild()发出新添加的子节点。顺便说一句,您发布的代码(与屏幕截图不同)不完整 -
@MathiasR.Jessen 为了简单起见,我只删除了
[xml]$doc=....之后的三行。不影响问题。 -
它让
main()函数抛出一个错误(因为$computers不存在),还不如彻底删除它
标签: xml powershell return