Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Converts [PSObjects] into a format suitable for storing in a file, so you can dot-source hashtables.
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
}
}
}
Owner

JPRuskin commented Sep 28, 2016 edited

Yes, I'm more than a little aware how insane/awful lines 11-13 are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment