How to convert pscustomobject to string?

I have the following

$Json = '{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}'
$Sql = $Json | ConvertFrom-Json

this $Sql outputs

Authentication Kind Username Password EncryptConnection
------------------- -------- -------- -----------------
UsernamePassword someID1 Yu#gh456!ts True

now i want to convert this back to string (after having some some changes on the password)

{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"******","EncryptConnection":true}

$Sql = $Sql | out-string

however, out-string doesnt do the job. this is what i get back

Authentication Kind Username Password EncryptConnection
------------------- -------- -------- -----------------
UsernamePassword someID1 ****** True

2 Answers

The counterpart to ConvertFrom-Json is (surprise, surprise) ConvertTo-Json!

PS C:\> $Sql |ConvertTo-Json
{ "Authentication Kind": "UsernamePassword", "Username": "someID1", "Password": "Yu#gh456!ts", "EncryptConnection": true
}

use the -Compress switch parameter if you want a non-pretty version:

PS C:\> $Sql |ConvertTo-Json -Compress
{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}

If you want a shallow native text representation of a psobject use LanguagePrimitives.ConvertTo() (this is what you see error output from the pipeline binder for example):

PS C:\> [System.Management.Automation.LanguagePrimitives]::ConvertTo($Sql, [string])
@{Authentication Kind=UsernamePassword; Username=someID1; Password=Yu#gh456!ts; EncryptConnection=True}
8

Override ToString() method

Add-Member -MemberType ScriptMethod -InputObject $myObject -Name ToString -Value { "My custom Object ";Get-Date -DisplayHint Date } -Force

Must use Force to override!

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like