我有以下 JSON:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"field1": {
"value": "fillmein"
},
"field2": {
"value": "fillmein"
},
"field3": {
"value": "fillmein"
}
}
}
我需要能夠在不同點查找每個欄位,并填寫它們。例如:
"field1": {
"value": "newv-value"
}
到目前為止,我的 powershell 腳本中有以下代碼:
$parameters = Get-Content 'parameters.json' -raw | ConvertFrom-Json -Depth 20
Write-Output $parameters.Values
Write-Output $parameters.Values.psobject.Properties
我不清楚如何導航物件。兩個寫輸出陳述句都不回傳任何內容。
我也嘗試過使用 PSCustomObject,如下所示:
$parameters = [PSCustomObject] @ Get-Content 'parameters.json' -raw | ConvertFrom-Json -Depth 20
但是我弄亂了語法,因為我收到了帶有“@”的“無法識別的令牌”錯誤。
任何提示將不勝感激。
uj5u.com熱心網友回復:
更新 JSON 應該像這樣簡單:
$json = Get-Content 'parameters.json' -Raw | ConvertFrom-Json
$json.parameters.field1.value = 'hello'
$json.parameters.field2.value = 'world'
$json | ConvertTo-Json
結果將是:
{
"$schema": "https://schema.management.azure.com/schemas/....,
"contentVersion": "1.0.0.0",
"parameters": {
"field1": {
"value": "hello"
},
"field2": {
"value": "world"
},
"field3": {
"value": "fillmein"
}
}
}
至于,如何導航你的物件,我想關鍵是使用Get-Member:
PS /> $json | Get-Member -MemberType Properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
$schema NoteProperty string $schema=https://schema.management.azure.com/schemas/...
contentVersion NoteProperty string contentVersion=1.0.0.0
parameters NoteProperty System.Management.Automation.PSCustomObject paramete...
PS /> $json.parameters | Get-Member -MemberType Properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
field1 NoteProperty System.Management.Automation.PSCustomObject field1=@{value=fillmein}
field2 NoteProperty System.Management.Automation.PSCustomObject field2=@{value=fillmein}
field3 NoteProperty System.Management.Automation.PSCustomObject field3=@{value=fillmein}
PS /> $json.parameters.field1 | Get-Member -MemberType Properties
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
value NoteProperty string value=fillmein
uj5u.com熱心網友回復:
我相信“.values.psobject”是不必要的。嘗試以下操作:
$myjson= Get-Content 'parameters.json' -raw | ConvertFrom-Json -Depth 20
$parameters.parameters.filed = "new-value"
ConvertTo-Json $myjson -Depth 20 | set-content .\parameters.json
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/437373.html
