2017-05-07 151 views
1

如何遍歷JSON文件中的所有項目?當前的代碼只是寫在一個大線所有名稱:使用PowerShell循環瀏覽JSON文件

Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json | ForEach-Object { 
    Write-Host $_.Name 
} 

JSON文件:

[ 
    { 
     "Name":"EnableRetry", 
     "Description":"Enable retry for Webservice Task", 
     "Type":"Boolean", 
     "Sensitive":false, 
     "Value":true 
    }, 
    { 
     "Name":"FolderStageFiles", 
     "Description":"Location of stage files", 
     "Type":"String", 
     "Sensitive":false, 
     "Value":"d:\\sources\\" 
    }, 
    { 
     "Name":"FtpPassword", 
     "Description":"Secret FTP password", 
     "Type":"String", 
     "Sensitive":true, 
     "Value":"Welcome1" 
    } 
] 
+1

重複從http ://stackoverflow.com/questions/33520699/iterating-through-json-file-powershell? –

回答

1

我最終選擇,對象和一個foreach - 對象:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json 

$JSON | Select-Object -Property Name,Description,Type,Sensitive,Value | ForEach-Object { 
    Write-Host $_.Name $_.Value 
} 
+0

看起來像是一個很好的解決方案給我。對於不回覆你的道歉。 –

+0

沒問題,我把你的代碼作爲基礎,並幫助我......幾天後將完整的代碼發佈在我的博客上。 – Joost

+0

這是完整的代碼,如果有人想複製它:http://microsoft-ssis.blogspot.com/2017/05/import-and-export-ssis-catalog.html – Joost

1

如果你這樣做:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json 

$JSON將是一個PowerShell對象包含具有在JSON文件中定義的所有屬性的對象集合。

在控制檯輸入$JSON,您將看到此對象的內容。

要訪問特定項目的特定屬性的集合中,你可以(例如)做:

$JSON | Where {$_.Name -eq 'FolderStageFiles'} | Select -ExpandProperty Value 
+0

有沒有什麼東西循環通過集,因爲我不知道json文件的值......只有結構(名稱,描述,類型,敏感和價值)。 我想遍歷這些記錄並將這些值添加到SSIS環境,如http://microsoft-ssis.blogspot.com/2015/08/deploying-environments-and-variables.html – Joost