Skip to content

Instantly share code, notes, and snippets.

@iainbrighton
Created June 2, 2016 13:37
Show Gist options
  • Save iainbrighton/38fcbb1dfa2aedde8908131a2eb8b970 to your computer and use it in GitHub Desktop.
Save iainbrighton/38fcbb1dfa2aedde8908131a2eb8b970 to your computer and use it in GitHub Desktop.
Convert-HashToString
function Convert-HashToString {
[CmdletBinding()]
[OutputType([System.String])]
param (
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[System.Collections.Hashtable] $Hashtable,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Int32] $Indentation,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Int32] $Offset,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Management.Automation.SwitchParameter] $Flatten
)
begin {
function ToHashString {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[System.String] $Key,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[System.String] $Value,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Int32] $Indentation,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Int32] $Offset,
[Parameter(ValueFromPipelineByPropertyName)]
[System.Management.Automation.SwitchParameter] $Flatten
)
process {
if ($Flatten) {
[ref] $null = $stringBuilder.AppendFormat(' {0} = {1};', $Key, $Value);
}
else {
$indentString = '{0}{1}' -f (' ' * $Offset), (' ' * $Indentation);
[ref] $null = $stringBuilder.AppendFormat('{0}{1} = {2}', $indentString, $Key, $Value).AppendLine();
}
}
} #end function ToHashString
}
process {
$stringBuilder = New-Object -TypeName System.Text.StringBuilder;
if ($Flatten) {
[ref] $null = $stringBuilder.Append('@{');
}
else {
$indentString = ' ' * $Offset;
[ref] $null = $stringBuilder.Append($indentString).AppendLine('@{');
}
foreach ($key in $Hashtable.Keys) {
$value = $Hashtable[$key];
if ($key -match '\s') {
$key = "'$Key'";
}
if ($value -is [string]) {
$stringValue = "'{0}'" -f $value;
}
elseif ($value -is [bool]) {
$stringValue = '${0}' -f $value.ToString();
}
##elseif ($value -is [array]) {
## $value = Convert-ArrayToString -Array $value -Flatten:$Flatten
## [ref] $null = $stringBuilder.Append(" $key = $value;");
##}
elseif ($value -is [hashtable]) {
$stringValue = Convert-HashToSTring -Hashtable $value;
}
elseif ($value -is [pscredential]) {
$stringValue = '[PSCredential <{0}>]' -f $value.UserName;
}
else {
## Just call .ToString() on any other type, e.g. integers
$stringValue = $value.ToString();
}
ToHashString -Key $key -Value $stringValue -Flatten:$Flatten -Offset:$Offset -Indent:$Indentation;
}
if ($Flatten) {
[ref] $null = $stringBuilder.Append(' }');
}
else {
$indentString = ' ' * $Offset;
[ref] $null = $stringBuilder.Append($indentString).Append('}');
}
return $stringBuilder.ToString();
}
} #end function Convert-HashToString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment