Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Last active September 28, 2016 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPRuskin/e24bd5c6d2a7c95fca50f4a7d7755497 to your computer and use it in GitHub Desktop.
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.
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
}
}
}
@JPRuskin
Copy link
Author

JPRuskin commented Sep 28, 2016

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