Expand-Object.psm1

<#
.SYNOPSIS
Exports a JSON object to key=value pairs.

.DESCRIPTION
The Expand-Object function takes a JSON object and recursively expands its properties into key=value pairs. This script wraps that function in a CmdletBinding and adds some parameter handling, allowing it to be used as a cmdlet.

.PARAMETER InputObject
The JSON object to expand. This should be piped in or passed via the pipeline.

.EXAMPLE
$object = [PSCustomObject]@{
    Name = 'John Doe'
    Age = 30
    Address = @{
        Street = '123 Main St.'
        City = 'Anytown'
        State = 'CA'
    }
}
$object | Export-Object -Prefix "Person"

This example exports a JSON object to key=value pairs. The resulting keys will have the prefix "Person".

.NOTES
Written by Paulo Correia
#>

function Expand-Object {
[CmdletBinding()]
param (
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    $InputObject
)

    # Define a helper function to flatten the JSON object
    function Expand-Object {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $InputObject,
        [Parameter(Mandatory=$false)]
        [string] $Prefix="",
        [Parameter(Mandatory=$false)]
        [string] $Separator=""

    )

    begin {
        if ([System.Environment]::OSVersion.Platform -eq 'Win32NT') {
            $Separator = ':'
        } else {
            $Separator = '__'
        }
    }

    process {
        foreach ($Property in $InputObject.PsObject.Properties) {
            $Name = $Property.Name -replace '[^a-zA-Z0-9_]','_'
            $Value = $Property.Value

            if ($Value -is [System.Management.Automation.PSCustomObject]) {
                $NewPrefix = if ($Prefix) {"$Prefix$Separator$Name"} else {$Name}
                $Value | Expand-Object -Prefix $NewPrefix -Separator $Separator
            } else {
                $Output = if ($Prefix) {"$Prefix$Separator$Name=$Value"} else {"$Name=$Value"}
                Write-Output $Output
            }
        }
    }

    end {
        # Clean up any resources here, if necessary
    }
    }

    Expand-Object -InputObject $InputObject
}