PowerShell function to Convert PSCustomObject to HashTable.
<#
.SYNOPSIS
Convert PSCustomObject to HashTable
.DESCRIPTION
Convert PSCustomObject to HashTable
.EXAMPLE
Get-Content "test.json" | ConvertFrom-Json | ConvertTo-HashTable
#>
function ConvertTo-HashTable
{
[CmdletBinding()]
Param(
[parameter(ValueFromPipeline)]
[PSCustomObject] $object,
[switch] $recurse
)
$ht = @{}
if ($object)
{
$object.PSObject.Properties | ForEach-Object {
if ($recurse -and ($_.Value -is [PSCustomObject]))
{
$ht[$_.Name] = ConvertTo-HashTable $_.Value
}
else
{
$ht[$_.Name] = $_.Value
}
}
}
$ht
}
Export-ModuleMember -Function ConvertTo-HashTable
# --------------------------
# Option 2:
# --------------------------
function ConvertTo-HashTable2
{
<#
.SYNOPSIS
Converts a PSObjects NoteProperties to HasbTable.
.EXAMPLE
$data = Import-Csv file.csv
foreach ($item in ($data | ConvertTo-HashTable2))
{
# Invoke-RestMethod @item
$item
}
.LINK
https://github.com/dfinke/OneGetGistProvider/blob/master/GistProvider.psm1
#>
param(
[Parameter(ValueFromPipeline)]
$Data
)
process
{
if (-not $fields)
{
$fields = ($Data | Get-Member -MemberType NoteProperty).Name
}
$hashTable = [Ordered]@{}
foreach ($field in $fields)
{
$hashTable.$field = $Data.$field
}
$hashTable
}
}