2016-05-08 29 views
1

我試圖將自定義屬性添加到內置的PowerShell類型,然後將該對象轉換爲Json。我遇到的問題是ConvertTo-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,那麼它的工作原理。例如。

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

任何人都可以解釋爲什麼發生這種情況?

+1

PowerShell v2不包含'ConvertTo-Json' cmdlet。如果你使用一些自定義實現,那麼你應該指定哪一個。 – PetSerAl

+0

固定。問題仍然發生在PS> = 3.0的所有版本上 – arwan

+1

發生這種情況時,ConvertTo-Json只在看到「PSObject」時纔會查看自定義屬性。 – PetSerAl

回答

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進入JSON只有當你明確地投$aPSObject

相關問題