我正在尝试使用单个值更新JSON文件。该文件已更新,但正在使用我不想要或不需要的一堆额外数据进行更新。
以下是PowerShell脚本的代码段:
Id.txt包含一个字符串“16963e76”
$outPath = "C:\Program Files (x86)\Go Agent\pipelines\mypipeline\Application\Application\Id.txt"
$imageid = Get-Content $outPath
$filejson = Get-Content -Raw -Path $file.FullName -Encoding UTF8 | ConvertFrom-Json
$filejson.parameters.Image = $imageid
$filejson | ConvertTo-Json | Out-File $filepath -Encoding utf8 -Force
这就是我希望我的JSON看起来像:
{
"name": "perf-a",
"cft_file":"cft/cft.json",
"parameters": {
"AppEnvironmentType": "perf",
"Image": "16963e76"
},
"tags": {
"Owner": "email@me.com",
"CostCenter": "12345"
}
}
以下是我的JSON在更新后的实际情况:
{
"name": "perf-a",
"cft_file": "cft/cft.json",
"parameters": {
"AppEnvironmentType": "perf",
"Image": {
"value": "16963e76",
"PSPath": "C:\\Program Files (x86)\\Go Agent\\pipelines\\mypipeline\\Application\\Application\\Id.txt",
"PSParentPath": "C:\\Program Files (x86)\\Go Agent\\pipelines\\mypipeline\\Application\\Application",
"PSChildName": "Id.txt",
"PSDrive": "C",
"PSProvider": "Microsoft.PowerShell.Core\\FileSystem",
"ReadCount": 1
}
},
"tags": {
"Owner": "email@me.com",
"CostCenter": "12345"
}
}
导致此问题的原因是什么?如何阻止它发生?
谢谢,
朗达
答案 0 :(得分:1)
修改
为解决方案工作添加了正确的理由。
好的,当你从id.txt导入字符串时,powershell会从环境中添加几个noteproperties,通常这些并不重要,可以忽略。
然而,ConvertTo-JSON从对象中提取这些注释属性并将它们插入到json中。通过使用tostring方法,我的解决方案通过将字符串更改为另一个字符串来工作,但这次没有note属性,因此它可以工作。
$outPath = "C:\Program Files (x86)\Go Agent\pipelines\mypipeline\Application\Application\Id.txt"
$imageid = (Get-Content $outPath)ToString()
$filejson = Get-Content -Raw -Path $file.FullName -Encoding UTF8 | ConvertFrom-Json
$filejson.parameters.Image = $imageid
$filejson | ConvertTo-Json | Out-File $filepath -Encoding utf8 -Force
以前不正确的原因:
$ imageid实际上是一个对象,当你导入它时,convertto-json将整个对象放入你的文件中。
你应该确保$ imageid只是一个字符串,虽然有几种方法可以使用tostring方法,如下所示。
答案 1 :(得分:0)
可能会改变这个:
`$filejson.parameters.Image = $imageid.value`
因为您正在将对象传递给$filejson.parameters.Image
,但您只需要该对象的1个属性。