How to Convert Pscustomobject to String?
I Have the Following $Json = '{"Authentication Kind":"Usernamepassword","Username":"Someid1","Password":"Yu#Gh456! Ts","Encryptconnection": True}' $Sql = $Json...
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}
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!