I have a PowerShell script that will pull the JSON from an API call and add in an additional value however, in the call that is made after shows the added value in double-quotes as well as backslashes on the double quotes. Any ideas what might be wrong and how to address this issue?
$Exclusion = @{};
# The Value here needs to have a slash but cant get it working
$Exclusion | Add-Member -Type NoteProperty -Name 'path' -Value '\stuff'
$Exclusion | Add-Member -Type NoteProperty -Name 'violations' -Value @()
$Exclusion = $Exclusion | ConvertTo-Json -Compress
write-Host $Exclusion
$policyWebResponse.memoryviolation.memory_exclusion = $Exclusion
The result when I print the value of the $Exclusion looks good
write-Host $Exclusion:
{"path":"\\stuff","violations":[]}
However, when it runs the POST the output shows as
"{\"path\":\"\\\\stuff\",\"violations\":[]}"
#Debug
Write-Host("Policy dump: ");
Write-Host $newPolicyJson
Results:
"memory_exclusion": [
{
"violations": [],
"path": "\\existing\path"
},
"{\"path\":\"\\\\stuff\",\"violations\":[]}"
],
"memory_exclusion_list": [
"\\existing\path2"
]
},
Result: "{\"path\":\"\\\\stuff\",\"violations\":[]}"
Want: {"path":"\\stuff","violations":[]}
CodePudding user response:
The problem comes as somewhere in the process you let the convertto-json cmdlet run twice.
'{"path":"\\stuff","violations":[]} '| ConvertTo-Json
is exactly the result, youre getting
Btw, your code is a little bit weird. You create a hashtable, but then you add the members via Add-Member.
Either use
$Exclusion = @{};
$Exclusion.path = '\stuff'
$Exclusion.violations = @()
or when you prefer a PSCustomObject
$Exclusion = [PSCustomObject]@{
path = '\stuff';
violations= @()
}