如何使用Powershell仅在JSON元素不存在时添加对应元素
PowerShell 给JSON文件追加指定属性的实现方案
完整实现代码
$targetPath = "C:\Users\me\AppData\Roaming\UnityHub\editors.json" $targetVersion = "2020.3.19f1" $FileContent = Get-Content -Path $targetPath -Raw | ConvertFrom-Json if ( ($FileContent | Get-Member -MemberType NoteProperty -Name $targetVersion) -ne $null ) { Write-Host "it exists" } else { Write-Host "add it" # 构造待添加的内容对象 $newEditorEntry = [PSCustomObject]@{ version = $targetVersion location = @("C:\Program Files\Unity\Hub\Editor\2020.3.19f1\Editor\Unity.exe") manual = $true } # 给原JSON转换后的对象追加属性 Add-Member -InputObject $FileContent -MemberType NoteProperty -Name $targetVersion -Value $newEditorEntry # 转换回JSON并写入文件,指定深度避免嵌套内容被截断,指定编码避免乱码 $FileContent | ConvertTo-Json -Depth 10 | Set-Content -Path $targetPath -Encoding UTF8 }
关键逻辑说明
- 用
Add-Member可以动态给PSCustomObject类型的对象添加自定义属性,不会修改原有已存在的属性值,满足保留原有数据的需求 ConvertTo-Json默认序列化深度为2,如果不指定更高的深度值,会导致嵌套的location数组等内容被截断为[ ... ]占位符,这里设置-Depth 10足够覆盖大部分场景- 写入文件时指定
-Encoding UTF8,保证路径中的特殊字符、中文内容不会出现编码错误
内容的提问来源于stack exchange,提问作者DaveA
相关产品推荐
相关产品推荐

