xml - 无法阻止 PowerShell 更改返回对象的类型

标签 xml powershell return

当我从函数返回 XML 对象时,PowerShell 将其类型更改为 Object[] :

enter image description here

我在这里读到:
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/

相关文章:

php - 在 PHP 中通过引用返回

Python:当 False 时继续执行脚本的 if/elif 函数?

c# - XML Unicode 安全编码

powershell - 如何在win10命令提示符下使用ffmpeg连接来自不同子目录的视频文件?

java - 一组用于两个相同命名空间的 JAXB 类

Powershell:从 runas/netonly 启动时发现默认网络凭据

image - 通过命令行合并图像

vb.net - 语法:VB.NET 子例程中的 "Exit Sub"或 "Return"

html - libxml2 无法正确处理 HTML 中的 CDATA

asp.net-mvc - ASP.NET MVC : Making an Xdocument available to jquery?