Skip to content

Instantly share code, notes, and snippets.

@a-bronx
Created January 23, 2017 07:08
Show Gist options
  • Save a-bronx/26ed031457a2e94270308854b2b9583e to your computer and use it in GitHub Desktop.
Save a-bronx/26ed031457a2e94270308854b2b9583e to your computer and use it in GitHub Desktop.
<# 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