Cataster
Cataster

Reputation: 3481

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

Upvotes: 1

Views: 16196

Answers (3)

Beau
Beau

Reputation: 29

If you want it to look how it looks in the console, but in Format-List, and not in JSON format like @mathias-r-jessen's answer, use the following:

PS C:\> Write-Output "$(Out-string -InputObject ($sql|Format-List))"

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

Upvotes: 0

David Morrow
David Morrow

Reputation: 294

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!

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

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}

Upvotes: 2

Related Questions