繁体   English   中英

使用PowerShell遍历JSON文件

[英]Looping through JSON file with 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"
   }
]

我最终选择对象和一个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
}

如果您这样做:

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

$JSON将是一个PowerShell对象,其中包含具有JSON文件中定义的所有属性的对象的集合。

在控制台上输入$JSON ,您将看到此对象的内容。

要访问集合中特定项目的特定属性,您可以执行以下操作(例如):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM