Created
January 23, 2017 07:08
-
-
Save a-bronx/26ed031457a2e94270308854b2b9583e to your computer and use it in GitHub Desktop.
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
<# Object initializer syntax ( $config = @{ … } ) produces a Hashtable. | |
Unlike this, the ConvertFrom-Json function returns PSCustomObject instead. | |
This may be inconvenient if you keep configuration both in JSON files and in PS1 files. | |
To keep uniformity, convert object to Hashtable using this function | |
#> | |
function ConvertTo-Hashtable { | |
param( | |
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] | |
$InputObject | |
) | |
# handle collections of PSObject | |
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [String]) { | |
$collection = @( | |
foreach ($object in $InputObject) { | |
ConvertTo-Hashtable $object | |
} | |
) | |
Write-Output -NoEnumerate $collection | |
} | |
# handle PSObjects | |
elseif ($InputObject -is [PSObject]) { | |
$h = @{} | |
$InputObject.PSObject.Properties | %{ | |
$h[$_.Name] = ConvertTo-Hashtable $_.Value | |
} | |
return $h | |
} | |
else { | |
return $InputObject | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment