更新时间:2023-01-17 18:36:18
好的,这就是我的操作方式,因此至少可以在Windows 2008的PowerShell v2上运行.
Ok, so here is how I did it so it works down to at least PowerShell v2 on Windows 2008.
首先,为您要使用的版本加载Json.NET程序集,我选择了.NET 3.5版本:
First, load the Json.NET assembly for the version you would like to use, I took the .NET 3.5 version:
[Reflection.Assembly]::LoadFile("Newtonsoft.Json.dll")
我在文件中包含JSON,因为它已在我编写的部署配置中使用,因此我需要读取文件,然后解析JSON
I had the JSON in a file since it was used in a deployment configuration I wrote, so I needed to read the file and then parse the json
$json = (Get-Content $FileName | Out-String) # read file
$config = [Newtonsoft.Json.Linq.JObject]::Parse($json) # parse string
现在要从配置中获取值,您需要使用Item
方法,该方法似乎是PowerShell在哈希表/字典上定义的.因此,要获得一个简单字符串的项目,您应该编写:
Now to get values from the config you need to to use the Item
method which seems defined by PowerShell on hashtables/dictionaries. So to get an item that is a simple string you would write:
Write-Host $config.Item("SomeStringKeyInJson").ToString()
如果您有各种各样的东西,则需要做类似的事情
If you had an array of things you would need to do something like
$config.Item("SomeKeyToAnArray") | ForEach-Object { Write-Host $_.Item("SomeKeyInArrayItem").ToString() }
要访问您编写的嵌套项目
To access nested items you write
$config.Item("SomeItem").Item("NestedItem")
这就是我解决了在PowerShell中使用Json.NET解析JSON的方式.
That's how I solved parsing JSON with Json.NET in PowerShell.