![](/img/trans.png)
[英]Get class of returned object by PowerShell command - determine a cmdlet's output data type
[英]PowerShell cmdlet is changing the type of the returned object
这种行为是令人迷惑的!
考虑以下PowerShell脚本:
[Reflection.Assembly]::LoadFrom("Newtonsoft.Json.dll") | Out-Null
function ConvertFrom-JsonNet {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string] $Json
)
$O = [Newtonsoft.Json.Linq.JObject]::Parse($Json)
Write-Host $O.GetType().Name
return $O
}
Clear-Host
$Json = '{"test":"prop"}'
$O1 = ConvertFrom-JsonNet '{"test":"prop"}'
$O2 = [Newtonsoft.Json.Linq.JObject]::Parse($Json)
Write-Host $O1.GetType().Name
Write-Host $O2.GetType().Name
您期望输出为:
JObject
JObject
JObject
但是不是! 它的:
JObject
JProperty
JObject
这怎么可能? 如何在函数中的对象的类型JObject
,但后来它传递出的功能后,它的JProperty
?
叹
是的,PowerShell的灵活性很强!
显然,PowerShell将“展开”所有发往管道的集合。 在这种情况下, JObject
实现ICollection<KeyValuePair<string, JToken>>
。 JObject
的集合包含一个JProperty
,它是“展开”到管道中的东西。 我找到了这个答案,这表明将一个集合滚动到一个外部集合中会导致将预期的值放置在管道中。
如果PowerShell具有未更改即可向管道中添加内容的机制,这会很好吗? :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.