2016-12-05 116 views
1

我試圖用單個值更新JSON文件。該文件已更新,但正在更新一些額外的數據,我不想或不需要。使用PowerShell更新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 protected]", 
    "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 protected]", 
     "CostCenter": "12345" 
    } 
} 

是什麼導致了這個問題,我該如何阻止它發生?

感謝,

朗達

+1

行,所以當您導入從id.txt PowerShell中的字符串是從環境中添加幾個noteproperties,通常這些並不重要,可以忽略。然而ConvertTo-JSON從對象中提取這些音符屬性並將它們插入到你的json中。 通過使用tostring方法,我的解決方案通過改變什麼是一個字符串到另一個字符串,但這次沒有註釋屬性,所以它的工作原理。 –

回答

0

可能更改此:

`$filejson.parameters.Image = $imageid.value` 

由於您所傳遞對象到$filejson.parameters.Image,但你只需要該對象的1財產。

+1

此解決方案不工作 –

+0

'$ imageid'是'[字符串]'實例(由於已經分配從'輸出給Get-Content'應用於單個行輸入文件),所以它不具有一個'.value'屬性(它被PS添加了音符屬性,然而,正如Jim的答案所解釋的那樣)。 – mklement0

+0

P.S.:問題中JSON輸出中的'value'屬性是'ConvertTo-Json'對如何用'NoteProperty'和/或'ScriptProperty'成員裝飾的值類型和字符串進行字符串化的人爲因素。 – mklement0

1

編輯

增加了正確的解決方案工作原因。

好吧,當你從id.txt中導入字符串時,powershell會從環境中添加幾個noteproperties,通常這些都不重要,可以忽略。

不過的ConvertTo-JSON是從對象抽出這些音符的屬性和它們插入到你的JSON。通過使用tostring方法,我的解決方案通過將字符串更改爲另一個字符串來工作,但這次沒有註釋屬性,因此它可以工作。

$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 

上一個不正確原因:

的$圖像標識實際上是當你導入像和的ConvertTo-JSON是把完整的對象到你的文件的對象。

你應該確保$圖像標識只是一個字符串,雖然有這樣做的幾種方法,你可以使用toString方法如下。