powershell 如何将pscustomobject转换为string?

r8uurelv  于 2023-06-23  发布在  Shell
关注(0)|答案(3)|浏览(136)

我有以下内容

$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

现在我想把它转换回字符串(在密码上有一些变化之后)
{“身份验证种类”:“用户名密码”,“用户名”:“someID 1”,“密码”:“******",“EncryptConnection”:true}

$Sql = $Sql | out-string

但是,out-string不能完成这项工作。这就是我得到的回报

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

8zzbczxx1#

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()(例如,这是你在pipeline binder中看到的错误输出):

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

nbewdwxp2#

重写ToString()方法
Add-Member -MemberType ScriptMethod -InputObject $myObject -Name ToString -Value {“我的自定义对象“; Get-Date -DisplayHint Date } -Force
必须使用武力来覆盖!

bzzcjhmw

bzzcjhmw3#

如果你想让它看起来像在控制台中一样,但在Format-List中,而不是像@mathias-r-jessen的答案那样的JSON格式,请使用以下内容:

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

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

相关问题