2017-10-16 31 views
0

我是Powershell的新手。我有以下PS腳本。我試圖確定powershell的「代碼」來確定哪個(如果有的話)「字段」是一個數組或哈希表。源文本是一個json文件。試圖識別代碼中的PS對象元素類型

$txt = @" 
{ 
    "id": "02002010", 
    "booktitle": "", 
    "pagetitle": "Demo Page", 
    "parent": "02002000", 
    "img": [ 
    { 
     "imgfile": "02A.png", 
     "imgname": "02A.png" 
    } 
    ], 
    "fmt": "", 
    "entries": [ 
    { 
     "itemid": "1", 
     "partnumber": "1234567", 
     "partdescription": "Washer", 
     "partqty": "2", 
     "Manufacturer": "ACME", 
     "TYPE": "Stainless", 
     "partdescriptionlocal": "Washer" 
    }, 
    { 
     "itemid": "2", 
     "partnumber": "98765-B", 
     "partdescription": "Screw", 
     "partqty": "8", 
     "Manufacturer": "Widget Inc", 
     "TYPE": "Galv", 
     "partdescriptionlocal": "Screw" 
    }] 
} 
"@ 
$json= ConvertFrom-Json -inputobject $txt 
foreach($pct in $json) { 
$pct} 

腳本的輸出

id  : 02002010 
booktitle : 
pagetitle : Demo Page 
parent : 02002000 
img  : {@{imgfile=02A.png; imgname=02A.png}} 
fmt  : 
entries : {@{itemid=1; partnumber=1234567; partdescription=Washer; partqty=2; Manufacturer=ACME; TYPE=Stainless; 
      partdescriptionlocal=Washer}, @{itemid=2; partnumber=98765-B; partdescription=Screw; partqty=8; 
      Manufacturer=Widget Inc; TYPE=Galv; partdescriptionlocal=Screw}} 

我的問題:

什麼屬性/參數???標識img條目作爲其值爲數組的「字段」 我試圖識別使用PS而不明確知道每個字段名稱的這樣的字段(子陣列)。

在此先感謝。

回答

1

.gettype()方法的.basetype屬性會給你:

json= ConvertFrom-Json -inputobject $txt 
foreach($pct in $json) { 
$pct.psobject.properties.name | 
foreach-object { 
    [PSCustomObject]@{ 
    Property = $_ 
    Type = $pct.$_.gettype().basetype 
    } 
} 
} 

Property Type   
-------- ----   
id  System.Object 
booktitle System.Object 
pagetitle System.Object 
parent System.Object 
img  System.Array 
fmt  System.Object 
entries System.Array 
+0

或者,他們可以只使用PSObject的屬性列表的TypeNameOfValue財產,並記住,任何在結束'[]'是一個數組:'$ json.psobject.Properties | FT名稱,TypeNameOfValue' – TheMadTechnician

+0

謝謝mjolinor和TheeMatechnician。我可以問另一個方面嗎?有沒有一種簡單的技術來識別那些具有System.array屬性的元素。也就是說,不管json文件如何,我可以識別那些具有system.array屬性的元素/字段嗎? – Orange

+0

對不起拼寫錯誤的TheMadTechnician ---粘鍵和沒有足夠的評論。我確實發現了$ json.psobject.Properties |其中typenameofvalue -eq「system.object []」| ft名稱,typenameofvalue獲取名稱TypeNameOfValue ---- --------------- img System.Object [] entries System.Object [] – Orange