2017-05-07 96 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