【问题标题】:Can't prevent PowerShell from changing the return object's type无法阻止 PowerShell 更改返回对象的类型
【发布时间】: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


【解决方案1】:

问题是函数输出 consists of everything that isn't captured 并且始终是一个 .NET 对象。

Function main(){

   [xml]$doc = New-Object System.Xml.XmlDocument

   $computer = getComputerXML $doc
   [void]$computers.AppendChild($computer)
}

您可以像这样检查[void]的有/无区别:

$computers| foreach {$_.GetType().Fullname}

return 关键字允许您在任何特定的时间退出函数 点,...但我们不需要像我们一样使用 return 关键字 在 C 风格的函数中。您也可以“可选地”指定一个参数 到将导致参数仅输出的 return 语句 在返回之前。 "return $xy" not 是否意味着函数 唯一的输出是 $xyvariable 的内容。 ...

您在编写 PowerShell 函数时必须勤奋,以确保 你只得到你想要的输出。这通常意味着重定向 不需要的输出到 $null (或可选地类型转换表达式 不需要的输出到[void])。

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2012-05-04
    • 1970-01-01
    • 2015-04-28
    • 2015-07-17
    • 1970-01-01
    相关资源
    最近更新 更多