Powershell 如何将pscustomobject转换为字符串?
我有以下几点Powershell 如何将pscustomobject转换为字符串?,powershell,Powershell,我有以下几点 $Json = '{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}' $Sql = $Json | ConvertFrom-Json 此$Sql输出 Authentication Kind Username Password EncryptConnection -------------------
$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”,“Username:“someID1”,“Password:“*******”,“EncryptConnection”:true}
但是,输出字符串
不起作用。这就是我得到的
Authentication Kind Username Password EncryptConnection
------------------- -------- -------- -----------------
UsernamePassword someID1 ****** True
与Json的转换相对应的是(惊喜,惊喜) 如果想要非美观版本,请使用
-Compress
开关参数:
PS C:\> $Sql |ConvertTo-Json -Compress
{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}
如果您想要psobject的浅层本机文本表示,请使用LanguagePrimitives.ConvertTo()
(例如,这就是您在管道绑定器中看到的错误输出):
虽然,如果它不是json,那么它是一个字符串,它是一个pscustomobject。如何将其转换回字符串?对于我的案例来说,这不相关或太重要,但对于其他未来的Visotr来说,这可能是一个很好的问题/答案:)更新了答案,尽管出于任何严肃的序列化目的,我强烈建议使用json、xml或(如果对象像您的示例中那样扁平)csv。哦,我的意思是没有@,因为@{象我说的那样象征pscustomobject,
converttojson
,Export-Clixml
(或Export-Xml
),转换为Csv
或导出Csv
是use@Cataster,您不能只为每个字符串创建一个PSCustomObject
。该字符串需要包含特定格式来定义单独的属性名称和值。通常这是一个序列化(“字符串化”)对象,如JSON、XML或类似PowerShell表达式的对象。您是否考虑了特定的字符串?
PS C:\> $Sql |ConvertTo-Json
{
"Authentication Kind": "UsernamePassword",
"Username": "someID1",
"Password": "Yu#gh456!ts",
"EncryptConnection": true
}
PS C:\> $Sql |ConvertTo-Json -Compress
{"Authentication Kind":"UsernamePassword","Username":"someID1","Password":"Yu#gh456!ts","EncryptConnection":true}
PS C:\> [System.Management.Automation.LanguagePrimitives]::ConvertTo($Sql, [string])
@{Authentication Kind=UsernamePassword; Username=someID1; Password=Yu#gh456!ts; EncryptConnection=True}