2

I have powershell script that I run in an installer while installation. I tried alot of examples to escape special characters, meaning if user choose username or password and that contains characters like slashes or commas, powershell fails to create json objects. Sometimes if user enters a comma, instead of taking it as a string, it breaks into json array. Following are my example and values for varibles are coming from installer, which are valid strings. Thank you for your insights.

$pathToJson = $InstalledPath+"appsettings.json"
$a = Get-Content $pathToJson | ConvertFrom-Json
$a.SQLConnectionSettings.SqlServerIp=$GkDbIP
$a.SQLConnectionSettings.SqlInitialCatalog=$GkDbName
$a.SQLConnectionSettings.SqlIntegratedSecurity=$SqlAuthType
$a.SQLConnectionSettings.SqlUserId=$GkDbUsername
$a.SQLConnectionSettings.SqlPassword=$SQLPassword
$a | ConvertTo-Json | set-content $pathToJson   

1 Answer 1

4

You can use Regex.Unescape to unscape the json content. For example:

$OBJECT = @{username="someone"; password="someone's \password"}
$OBJECT | ConvertTo-Json -depth 100 |
     % { [System.Text.RegularExpressions.Regex]::Unescape($_) } |
         Out-File "D:\somefile.json" -Encoding utf8

And here is the result:

{
    "password":  "someone's \password",
    "username":  "someone"
}

If you don't use unescape, the password will be saved as "someone\u0027s \\password".

Sign up to request clarification or add additional context in comments.

5 Comments

when I enter a comma, it broke string into array "SqlServerIp": [ "192.168.1.60", "1433\SQLEXPRESS01" ],
I tested with this: $OBJECT = @{username="someone"; password="someone's \password";SqlServerIp = @("192.168.1.60", "1433\SQLEXPRESS01")} and it worked as expected.
@("192.168.1.60", "1433\SQLEXPRESS01")} should be as one string "192.168.1.60,1433\SQLEXPRESS01". I am having headaches now with that back slash and commas. json file expects two slashes so that i can be escaped while user will enter only one in the installer textbox. Comma is breaking one string into array.
Probably you are doing it in a wrong way. I also tested $OBJECT = @{username="someone"; password="someone's \p,assword";SqlServerIp = "192.168.1.60,1433\SQLEXPRESS01"} and got the expected result. As a single string.
Is there a way to keep the order of the $OBJECT as defined while creating, when file is creating the json objects are not in order. Thank You Reza

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.