【问题标题】:PowerShell cmdlet is changing the type of the returned objectPowerShell cmdlet 正在更改返回对象的类型
【发布时间】:2015-06-25 20:42:25
【问题描述】:

这种行为很神秘!

考虑以下 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

这怎么可能? within函数JObject的对象的类型如何,但是传出函数后却是JProperty?

【问题讨论】:

  • JObject 实现了几个接口;其中之一是IEnumerable。 PowerShell 是否检测到它实现了IEnumerable 并在将对象放在管道上时扩展它?

标签: powershell powershell-4.0 powershell-cmdlet


【解决方案1】:

叹息

感谢 PowerShell 的不灵活性!

显然,PowerShell 将“展开”所有以管道为目标的集合。在这种情况下,JObject 实现了ICollection<KeyValuePair<string, JToken>>。 JObject 的集合包含一个 JProperty,它被“展开”到管道中。我找到了this 的答案,这表明将集合滚动到外部集合中会导致将预期值放入管道中。

如果 PowerShell 有一种机制可以在不受影响的情况下向管道添加一些东西,那不是很好吗? :)

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2013-10-26
    • 2022-01-05
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    相关资源
    最近更新 更多