Skip to content

Instantly share code, notes, and snippets.

@1RedOne
Last active June 30, 2021 18:25
Show Gist options
  • Save 1RedOne/ebd7147f377738694446064a7768deef to your computer and use it in GitHub Desktop.
Save 1RedOne/ebd7147f377738694446064a7768deef to your computer and use it in GitHub Desktop.
ConvertTo-StringData - Converting a complex object into StringData
Function ConvertTo-StringData($object, $propertyOverride){
$fields = $object | get-member -MemberType NoteProperty
foreach($field in $fields){
if (IsArray($field)){
OutputArrayMember -object $object -field $field
}
else{
OutputMember -object $object -propertyName $field.name -propertyOverride $propertyOverride
}
}
}
Function IsArray($object){
$object.Definition -match '.*\[\].*'
}
Function OutputMember($object,$propertyName, $propertyOverride){
if ($propertyOverride){
"$($propertyOverride).$($propertyName)=$($object.$($propertyName))"
}
else{
"$($propertyName)=$($object.$($propertyName))"
}
}
Function OutputArrayMember($object, $field){
$global:testObject = $object
$global:testfield = $field
$base = $field.Name
$i = 0
foreach ($item in $object.$($field.Name)){
ConvertTo-StringData -object $object.$($field.Name)[$i] -propertyOverride "$base[$i]"
$i++
}
}
Function Drill ($object, $parentPath){
if ($null -ne $parentPath){
$parentPath = $parentPath+$function:parentPath
$parentPath = $parentPath.TrimStart('.')
}
$parentPath
#select next leaf
if (hasChildren $object){
"drilling down into $object"
$props = GetNoteProperties $object
$var = getObjectByProperty $object $props
drill $var -parentPath "$($parentPath).$($props.Name)"
}
else{
ConvertTo-StringData -object $object -propertyOverride $parentPath
$global:test = $object
}
}
Function hasChildren($object){
[bool](($object | gm -MemberType NoteProperty).Definition -match 'System.Management.Automation.PSCustomObject')
}
function GetNoteProperties($object){
get-member -InputObject $object -MemberType NoteProperty
}
function getObjectByProperty($object, $propertyName){
$object.$($propertyName.Name)
}
$json ='{
"name": "John",
"age": 30,
"married": true,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]}
'
$object = $json | ConvertFrom-Json
$object | ConvertTo-StringData
#result
age=30
cars[0].model=BMW 230
cars[0].mpg=27.5
cars[1].model=Ford Edge
cars[1].mpg=24.1
married=True
name=John
#complex json
$json2 = '
{ "Logging": { "LogLevel": { "Default": "None", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "None", "System.Net.Http.HttpClient.SDSEmployeeMaster.ClientHandler[100]": "None" } } }
'
$object2 = $json2 | convertfrom-json
drill $object2
Logging.LogLevel
Logging.LogLevel.Default=None
Logging.LogLevel.Microsoft=Warning
Logging.LogLevel.Microsoft.Hosting.Lifetime=None
Logging.LogLevel.System.Net.Http.HttpClient.SDSEmployeeMaster.ClientHandler[100]=None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment