PoshCode Archive  Artifact [4a520c741c]

Artifact 4a520c741cbfd51f81c97faa325d4b1890e104020cbbe5a1c27d96879cd3e390:

  • File ConvertTo-Hashtable.ps1 — part of check-in [9d83b3142b] at 2018-06-10 13:48:18 on branch trunk — Converts objects properties into key-value hashtable (user: Joel Bennett size: 1649)

# encoding: ascii
# api: powershell
# title: ConvertTo-Hashtable
# description: Converts objects properties into key-value hashtable
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: ConvertTo-Hashtable
# x-poshcode-id: 4968
# x-archived: 2014-03-10T23:01:58
# x-published: 2014-03-09T01:25:00
#
#
function ConvertTo-Hashtable {
  #.Synopsis
  #   Converts an object to a hashtable of property-name = value 
  PARAM(
    # The object to convert to a hashtable
    [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
    $InputObject,

    # Forces the values to be strings and converts them by running them through Out-String
    [switch]$AsString,  

    # If set, allows each hashtable to have it's own set of properties, otherwise, 
    # each InputObject is normalized to the properties on the first object in the pipeline
    [switch]$jagged,

    # If set, empty properties are ommitted
    [switch]$NoNulls
  )
  BEGIN { 
    $headers = @() 
  }
  PROCESS {
    if(!$headers -or $jagged) {
      $headers = $InputObject | get-member -type Properties | select -expand name
    }
    $output = @{}
    if($AsString) {
      foreach($col in $headers) {
        if(!$NoNulls -or ($InputObject.$col -is [bool] -or ($InputObject.$col))) {
          $output.$col = $InputObject.$col | out-string -Width 9999 | % { $_.Trim() }
        }
      }
    } else {
      foreach($col in $headers) {
        if(!$NoNulls -or ($InputObject.$col -is [bool] -or ($InputObject.$col))) {
          $output.$col = $InputObject.$col
        }
      }
    }
    $output
  }
}