Skip to content

Instantly share code, notes, and snippets.

@noahpeltier
Created June 20, 2024 17:44
Show Gist options
  • Save noahpeltier/459494f841b08f5bdfa3b634e6c1c3bb to your computer and use it in GitHub Desktop.
Save noahpeltier/459494f841b08f5bdfa3b634e6c1c3bb to your computer and use it in GitHub Desktop.
Convert a pscustomobject to a hasthtable
function Convert-ToHashtable {
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[PSCustomObject]$InputObject
)
process {
$hashTable = @{}
foreach ($property in $InputObject.PSObject.Properties) {
$value = $property.Value
if ($value -is [PSCustomObject]) {
$hashTable[$property.Name] = Convert-ToHashtable -InputObject $value
} elseif ($value -is [System.Collections.IEnumerable] -and
$value -notmatch 'char|byte|bool|date|string') {
$hashTable[$property.Name] = @()
foreach ($item in $value) {
if ($item -is [PSCustomObject]) {
$hashTable[$property.Name] += Convert-ToHashtable -InputObject $item
} else {
$hashTable[$property.Name] += $item
}
}
} else {
$hashTable[$property.Name] = $value
}
}
return $hashTable
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment