Export-HashTable

After seeing this amazing thread, I had a quick think about the problem mentioned here.

I wanted [to export] PowerShell Hashtables [to] the file [...] instead of JSON.
The reason this came up was that I was pulling configuration hashtables out of scripts and plac[ing] them into files. This worked when I was editing them by hand and just importing them in my scripts, but then I wanted to generate these config files or make updates to them and could not do it in any intuitive way.

This user wanted to use Hashtable formatting when exporting to files, instead of standard JSON (which has a pre-installed cmdlet). Like this:

@{ 
    HostName    = "Server"
    OS          = "Windows Server 2012 R2 Standard (x64)"
    Environment = "VMWorkstation"
    Role        = "BaseSystem"
}

Instead of this:

{
    "Environment" : "VMWorkstation",
    "HostName"    : "Server",
    "OS"          : "Windows Server 2012 R2 Standard (x64)",
    "Role"        : "BaseSystem"
}

I had a quick attempt at a function to do this. Turns out that you can do it very quickly, but it gets more interesting if you want to format it nicely.

function Export-HashTable {
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias('InputObject')]
        [PSObject]$HashTable,
        [String]$Path,
        [String]$Name
    )
    process {
        $divWidth = ($HashTable.Keys.Length | Measure-Object -Maximum).Maximum + 8

        $hashString = ("$(if($Name){"`$$Name = "})@" + ($HashTable | ConvertTo-JSON) -replace '":','"=' -replace '",
','"
').Split("`n") | %{if($_ -match '^(\W+"\w+")=') {
            $_ -replace '^(\W+"\w+")=',"$($Matches[1] + (' '*($divWidth - $Matches[0].Length)))="}
            else {$_}
        }
    }
    end {
        if ($Path) {
            Out-File -FilePath $path -InputObject $hashString -Encoding utf8
        }
        else {
            return $hashString
        }
    }
}

</script src="https://gist.github.com/JPRuskin/e24bd5c6d2a7c95fca50f4a7d7755497.js">

An up to date copy can be found here.