ConvertTo-Json无法转换添加到内置类型的自定义属性

时间:2016-05-08 10:44:25

标签: powershell powershell-v3.0

我正在尝试向内置PowerShell类型添加自定义属性,然后将对象转换为Json。我遇到的问题是ConvertTo-Json不会转换我正在添加的自定义属性。例如,

$Proc = Get-Process explorer
$Proc.Modules | %{
    $_ | Add-Member NoteProperty MyCustomProperty "123456" -PassThru
}

$Proc.Modules[0].MyCustomProperty -eq "123456"    
# Returns true

$Json = ConvertTo-Json ($Proc.Modules) -Depth 4
$Json -match "123456"   
# Returns false.  Expect it to be true

编辑:如果我在ConvertTo-Json中使用“select *”,那么它可以工作。 E.g。

$Json = ConvertTo-Json ($Proc.Modules | select *) -Depth 4
$Json -match "123456"   
# Returns true

有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

ConvertTo-Json似乎仅在看到PSObject实例时才会查看扩展属性。如果您传递未包装的对象,那么只有基础对象属性才会进入生成的JSON:

Add-Type -TypeDefinition @'
    using System;
    using System.Management.Automation;
    public class SomeType {
        public static SomeType NewInstanceWithExtendedProperty() {
            SomeType instance = new SomeType();
            PSObject.AsPSObject(instance).Properties.Add(new PSNoteProperty("ExtendedProperty", "ExtendedValue"));
            return instance;
        }
        public string SomeProperty {
            get {
                return "SomeValue";
            }
        }

    }
'@
$a=[SomeType]::NewInstanceWithExtendedProperty()
ConvertTo-Json ($a, [PSObject]$a)

此代码将返回:

[
    {
        "SomeProperty":  "SomeValue"
    },
    {
        "SomeProperty":  "SomeValue",
        "ExtendedProperty":  "ExtendedValue"
    }
]

正如您所看到的,ExtendedProperty仅在您明确将$a强制转换为PSObject时才会进入JSON。