Private/Utils/ConvertTo-HashtableFromPsCustomObject.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function ConvertTo-HashtableFromPsCustomObject {
  #requires -Version 3.0
  <#
      .SYNOPSIS
      Converts any powershell custom object to a custom hashtable.

      .DESCRIPTION
      Iterates through elements of a custom object and converts them to a corresponding items in a hashtable. Uses recursion to go deep into json object.

      .PARAMETER PSCustomObject
      PS Custom Object that should be converted to a hashtable

      .EXAMPLE
      ConvertTo-HashtableFromPsCustomObject -PSCustomObject SomePSCustomObject
      This will convert SomePSCustomObject to a corresponding hashtable

      .INPUTS
      Any Powershell Custom Object

      .OUTPUTS
      A hashtable
  #>

 
  [CmdletBinding()]
  [OutputType([HashTable])]
  param ( 
    [Parameter(Mandatory = $true,Position = 0,         
              ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
         
    [object[]]
    $PSCustomObject 
  ) 
  process { 
    foreach ($myPsObject in $PSCustomObject) { 
      $output = @{} 
      $myPsObject | Get-Member -MemberType *Property | ForEach-Object { 
        $value = $myPsObject.($_.name)
        if ($value -is [PSCustomObject]) {
          $value = ConvertTo-HashtableFromPsCustomObject -psCustomObject $value
        }
        $output.($_.name) = $value
      }
    $output
    } 
  }
}