puneet puneet -4 years ago 114
JSON Question

Powershell - Retain the text of all Enum properties with ConvertTo-Json

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


When I use the command with "ConvertTo-Json" like below

GetMsolDomain |ConvertTo-Json


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
}


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.

When I give the below command

get-msoldomain |Select-object @{Name='Status';Expression={"$($_.Status)"}}|ConvertTo-json


I get the output as

{
"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)"}}


This line is transforming only the Status Property and not the VerificationMethod property because that is what I am providing as input .

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"
}

Answer Source

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 to CSV and finally back to Json,

Like this:

Get-MsolDomain | ConvertTo-Csv | ConvertFrom-Csv | ConvertTo-Json
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download