PoshCode Archive  Artifact [e0b8f232a5]

Artifact e0b8f232a54859aa93ef4efce0dfbc3d39cce58427a11b627bfd54a13f8a7e2c:

  • File New-PSOCustomObject.ps1 — part of check-in [14d814d71d] at 2018-06-10 12:58:17 on branch trunk — This function will create a custom PSObject using a hashtable as input. (user: russellds size: 1723)

# encoding: ascii
# api: powershell
# title: New-PSOCustomObject
# description: This function will create a custom PSObject using a hashtable as input.
# version: 0.1
# type: function
# author: russellds
# license: CC0
# function: New-PSOCustomObject
# x-poshcode-id: 1543
# x-archived: 2015-05-04T21:57:05
# x-published: 2010-12-17T12:49:00
#
# It can also set the default properties of the custom object if you download Set-PSODefaultProperties function: http://poshcode.org/1542
#
# References:
# http://blogs.msdn.com/powershell/archive/2009/12/05/new-object-psobject-property-hashtable.aspx
# http://poshoholic.com/2008/07/03/essential-powershell-name-your-custom-object-types/
# http://poshoholic.com/2008/07/05/essential-powershell-define-default-properties-for-custom-objects/

function New-PSOCustomObject {
    param(
          [Parameter(Mandatory=$true)]
          [string]$Name,
          [Parameter(Mandatory=$true)]
          [hashtable]$Properties,
          [Parameter()]
          [string[]]$DefaultProperties,
          [Parameter()]
          [hashtable]$ScriptMethods
         )
    
    $object = New-Object PSObject -Property $Properties
    
    $object.PSObject.TypeNames[0] = "System.Management.Automation.PSCustomObject.$($Name)"
    
    # Move Script Methods to Set-PSObjectDefaultProperties.
    # 
    if( $ScriptMethods ) {
        foreach( $key in $ScriptMethods.Keys ) {
            $object | Add-Member -MemberType ScriptMethod -Name $key -Value $ScriptMethods[$key]
        }
    }
    
    if( $DefaultProperties ) {
        Set-PSODefaultProperties -Object $object -DefaultProperties $DefaultProperties
    }
    
    return $object
}