Powershell - 使用 ConvertTo-Json 保留所有 Enum 属性的文本 [英] Powershell - Retain the text of all Enum properties with ConvertTo-Json
问题描述
对于Get-Msoldomain"powershell 命令,我得到以下输出(我们称之为输出#1),其中名称、状态和身份验证是属性名称以下是它们各自的值.
For "Get-Msoldomain" powershell command-let I get the below output (lets call it Output#1) where Name, Status and Authentication are the property names and below are their respective values.
Name Status Authentication
myemail.onmicrosoft.com Verified Managed
当我使用带有ConvertTo-Json"的命令时,如下所示
When I use the command with "ConvertTo-Json" like below
GetMsolDomain |ConvertTo-Json
我得到了 Json 格式的以下输出(我们称之为输出#2).
I get the below output (lets call it Output#2) in Json Format.
{
"ExtensionData": {
},
"Authentication": 0,
"Capabilities": 5,
"IsDefault": true,
"IsInitial": true,
"Name": "myemail.onmicrosoft.com",
"RootDomain": null,
"Status": 1,
"VerificationMethod": 1
}
然而,问题是,如果您注意到两个输出中的 Status 属性,则它是不同的.VerificationMethod 属性也是如此.不使用 ConvertTo-JSon Powershell 给出文本,使用 ConvertTo-Json 给出整数.
However, the problem is, that if you notice the Status property in both the outputs, it's different. Same happens for VerificationMethod property. Without using the ConvertTo-JSon Powershell gives the Text, and with using ConvertTo-Json it gives the integer.
当我给出以下命令时
get-msoldomain |Select-object @{Name='Status';Expression={"$($_.Status)"}}|ConvertTo-json
我得到的输出为
{
"Status": "Verified"
}
但是,我想要一些东西,这样我就不必指定任何要转换的特定属性名称,就像我在上面指定的方式
However, I want something so that I don't have to specify any specific property name for it to be converted , the way I am specifying above as
Select-object @{Name='Status';Expression={"$($_.Status)"}}
此行仅转换 Status 属性而不是 VerificationMethod 属性,因为这是我提供的输入.
This line is transforming only the Status Property and not the VerificationMethod property because that is what I am providing as input .
问题:我可以为ConvertTo-Json"命令行开关提供一些通用的东西,以便它返回 ALL 枚举属性作为文本而不是整数,没有明确命名它们,所以我得到如下输出:
Question: Is there something generic that I can give to the "ConvertTo-Json" commandlet, so that It returns ALL the Enum properties as Texts and not Integers, without explicitly naming them, so that I get something like below as the output:
{
"ExtensionData": {
},
"Authentication": 0,
"Capabilities": 5,
"IsDefault": true,
"IsInitial": true,
"Name": "myemail.onmicrosoft.com",
"RootDomain": null,
"Status": "Verified",
"VerificationMethod": "DnsRecord"
}
推荐答案
好吧,如果你不介意走一趟 :) 你可以将它转换为 CSV,这将强制字符串输出,然后重新转换它从 CSV 返回到 PS Object,最后返回到 Json.
Well, if you don't mind to take a little trip :) you can convert it to CSV which will force the string output, then re-convert it back from CSV to PS Object, then finally back to Json.
像这样:
Get-MsolDomain | ConvertTo-Csv | ConvertFrom-Csv | ConvertTo-Json
- 如果您需要保留原始类型而不是将其全部转换为字符串,请参阅 mklement0 有用的答案...
这篇关于Powershell - 使用 ConvertTo-Json 保留所有 Enum 属性的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!