当我从函数返回 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
最佳答案
问题是函数输出consists of everything that isn't captured并且始终是 .NET 对象。
Function main(){
[xml]$doc = New-Object System.Xml.XmlDocument
$computer = getComputerXML $doc
[void]$computers.AppendChild($computer)
}
您可以查看with/out的区别
[void]
像这样:$computers| foreach {$_.GetType().Fullname}
The return keyword allows you to exit the function at any particular point, ... but we do not need to use the return keyword like we do in C style function. You may also "optionally" specify an argument to the return statement that will cause the argument to be output just before returning. "return $xy" does not mean that the functions only output is the contents of the $xyvariable. ...
You have to be diligent when you write a PowerShell function to ensure you get only the output you want. This usually means redirecting unwanted output to $null (or optionally type casting the expression with the unwanted output to [void]).
关于xml - 无法阻止 PowerShell 更改返回对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46264054/