如何防止 PowerShell 在字符串中添加 \

huangapple go评论77阅读模式
英文:

how to prevent PowerShell adding \ to a string

问题

PowerShell is escaping the double quotes and backslashes in your string, which is why you see the extra backslashes in your JSON. To prevent PowerShell from adding these escape characters, you can use single quotes instead of double quotes when constructing your JSON string. Here's the modified part of your script:

Replace this line:

$a.value= "[`"E_" + $nr2 + "`"]"

With this line:

$a.value= '[\"E_' + $nr2 + '\"]'

By using single quotes, PowerShell will treat the string as-is and won't escape the double quotes and backslashes within it. This should give you the desired JSON format without the extra backslashes.

英文:

I'm currently working with Powershell editing JSONs

My JSON looks like this:

   {
        "value":  ["E_"]
   }

I only want to add a specific number after E_.
The result should look like this:

{
"value": ["E_5"]
}

My PS Script:

$tdePath = 'C:\temp\tde.csv'

$dirName = Get-ChildItem -Path $rootDir -Filter TDE_Config.json -Recurse -ErrorAction SilentlyContinue -Force | Select-Object DirectoryName | Export-Csv $tdePath  -NoTypeInformation 



$importTDEJson = Import-Csv $tdePath -Encoding UTF8 | % {

[String]$nr = $_.DirectoryName.Split('\')[6].split(' ')[4] 

$full_path = $_.DirectoryName + "\TDE_Config.json"


[int]$nr2 = $nr -as [int] #Convert String to Int to convert 004 -> 4

$a = Get-Content $full_path -raw | ConvertFrom-Json




$a.value= "[`"E_" + $nr2 + "`"]" 
$a | ConvertTo-Json  | set-content $full_path -Force

}

Only excuting "[`"E_" + $nr2 + "`"]" returns the value I need.
For example if $nr2 = 145 it returns in ps console

["E_145"]

But my JSON looks like this:

{
"value": "[\"E_145\"]"
}

Why is powershell adding \ to my string?
How can I prevent powershell adding \ to my string?

答案1

得分: 3

只返回翻译好的部分:

您正在手动混合使用 JSON 和 ConvertTo-Json。PowerShell 正在对您插入的反斜杠进行 JavaScript 转义。只需像这样设置 $a.value

$a.value = @("E_$nr2")

这将创建一个数组,然后 JSON 转换将为您完成其余部分。

编辑:
这是一个概念验证示例:

$a = [pscustomobject]@{
   value = 'Something else'
}
$nr2 = 145
$a.value = @("E_$nr2") 
$a | ConvertTo-Json  

输出:

{
    "value":  [
                  "E_145"
              ]
}
英文:

You are mixing Json by hand and Json by ConvertTo-Json.
Powershell is doing javascript escaping of the backslashes you insert. Just set $a.value like this:

$a.value= @("E_$nr2")

That will create an array and the Json conversion will do the rest for you.

EDIT:
Here is a proof of concept:

$a = [pscustomobject]@{
   value = 'Something else'
}
$nr2 = 145
$a.value= @("E_$nr2") 
$a | ConvertTo-Json  

outputs:

{
    "value":  [
                  "E_145"
              ]
}

huangapple
  • 本文由 发表于 2020年1月3日 15:16:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定