PoshCode Archive  Artifact [0ab8e65581]

Artifact 0ab8e655812ed047fc05ff5316c29fd68741f1ea691cfa28a101b86a2874dc72:

  • File ConvertFrom-Hashtable-2.ps1 — part of check-in [f63615010a] at 2018-06-10 13:01:42 on branch trunk — Create PSObjects from hashtables. Supports converting nested hashtables, and joining multiple pipelined hashtables into one object using Join-Object (user: Joel Bennett size: 1793)

# encoding: ascii
# api: powershell
# title: ConvertFrom-Hashtable 2
# description: Create PSObjects from hashtables. Supports converting nested hashtables, and joining multiple pipelined hashtables into one object using Join-Object
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: ConvertFrom-Hashtable
# x-poshcode-id: 1819
# x-archived: 2016-04-26T12:25:02
# x-published: 2011-05-03T13:57:00
#
# Note that joining hashtables is usually as simple as adding them, and generating objects from them in PowerShell 2 is as simple as New-Object PSObject -Property $Hashtable — you really only need this script if you want to recursively convert nested hashtables.
#
#function ConvertFrom-Hashtable {
[CmdletBinding()]
   PARAM(
      [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
      [HashTable]$hashtable
   ,
      [switch]$Combine
   ,
      [switch]$Recurse
   )
   BEGIN {
      $output = @()
   }
   PROCESS {
      if($recurse) {
         $keys = $hashtable.Keys | ForEach-Object { $_ }
         Write-Verbose "Recursing $($Keys.Count) keys"
         foreach($key in $keys) {
            if($hashtable.$key -is [HashTable]) {
               $hashtable.$key = ConvertFrom-Hashtable $hashtable.$key -Recurse # -Combine:$combine
            }
         }
      }
      if($combine) {
         $output += @(New-Object PSObject -Property $hashtable)
         Write-Verbose "Combining Output = $($Output.Count) so far"
      } else {
         New-Object PSObject -Property $hashtable
      }
   }
   END {
      if($combine -and $output.Count -gt 1) {
         Write-Verbose "Combining $($Output.Count) cached outputs"
         $output | Join-Object
      } else {
         $output
      }
   }
#}