我有一个包含 3 个块的 json 文件,每个环境一个块,因此 dev preprod 和 prod。 我有一个脚本,它创建一些 azure 资源,例如应用程序注册表和安全组,当脚本完成时,它将其记录到 json 文件和相应的环境中。 如果我运行 dev 脚本,它将填充 json 上的 dev 块。 如果我然后运行 preprod 脚本,它将填充 json 中的 preprod 块,但会使 dev 块为空,因为它像完整文件一样被覆盖,我希望它保留其他块,只影响我正在更新的块。 这是我的代码。
if ($environment -eq "Development") {
$devBlock = @{
"Project" = $projectName
"tenant" = $tenantName
"AppRegId" = $spdetails.appId
"ProjectId" = $projectSubId
"projectsubname" = $projectSubName
"Date" = $date
"Username" = $actor
"RoGroup" = $RoGroupid.id
"FcGroup" = $FcGroupid.id
"environment" = $environment
}
}
elseif ($environment -eq "PreProduction") {
$preprodBlock = @{
"Project" = $projectName
"tenant" = $tenantName
"AppRegId" = $spdetails.appId
"ProjectId" = $projectSubId
"projectsubname" = $projectSubName
"Date" = $date
"Username" = $actor
"RoGroup" = $RoGroupid.id
"FcGroup" = $FcGroupid.id
"environment" = $environment
}
}
else {
$prodBlock = @{
"Project" = $projectName
"tenant" = $tenantName
"AppRegId" = $spdetails.appId
"ProjectId" = $projectSubId
"projectsubname" = $projectSubName
"Date" = $date
"Username" = $actor
"RoGroup" = $RoGroupid.id
"FcGroup" = $FcGroupid.id
"environment" = $environment
}
}
$data = @{
"dev" = $devBlock
"preprod" = $preprodBlock
"prod" = $prodBlock
}
# Convert the hashtable to a JSON string
$json = $data | ConvertTo-Json -Depth 10
# Define the path for the JSON file
$jsonFilePath = $projectName + ".json"
# Write the JSON string to the file
$json | Out-File -FilePath $jsonFilePath -Encoding utf8
Write-Output "JSON file created at $jsonFilePath"
还没有尝试过,还想不出什么。
您需要先加载现有的json数据(当然要检查它是否存在),以便您可以更新它。
简化示例:
$json = Get-Content $jsonFilePath
$data = $json | ConvertFrom-Json
if ($environment -eq "PreProduction") {
$data.preprod.Project="whatever updated you want"
}
$json = $data | ConvertTo-Json -Depth 10
$json | Out-File -FilePath $jsonFilePath -Encoding utf8
祝你好运。