如何将pscustomobject转换为字符串?

时间:2019-07-09 18:00:00

标签: powershell

我有以下

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

$Sql输出

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

现在我想将其转换回字符串(在对密码进行一些更改之后)

  

{“身份验证   类型“:” UsernamePassword“,”用户名“:” someID1“,”密码“:” ******“,” EncryptConnection“:true}

$Sql = $Sql | out-string

但是,out-string并没有完成这项工作。这就是我回来的

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

2 个答案:

答案 0 :(得分:1)

ConvertFrom-Json的对应对象是ConvertTo-Json(感到惊讶)!

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

如果要使用非漂亮的版本,请使用-Compress开关参数:

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

如果要使用psobject的浅本机文本表示形式,请使用LanguagePrimitives.ConvertTo()(例如,这是您从管道绑定程序看到的错误输出):

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

答案 1 :(得分:0)

覆盖 ToString() 方法

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

必须使用强制覆盖!