Last active
September 28, 2016 13:49
-
-
Save JPRuskin/e24bd5c6d2a7c95fca50f4a7d7755497 to your computer and use it in GitHub Desktop.
Converts [PSObjects] into a format suitable for storing in a file, so you can dot-source hashtables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, I'm more than a little aware how insane/awful lines 11-13 are.