New-GenericObject.ps1 2.08 KB
Newer Older
O'Reilly Media, Inc committed
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
##############################################################################
##
## New-GenericObject
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Creates an object of a generic type. If using PowerShell version three,
use this syntax:

PS > $r = New-Object "System.Collections.Generic.Dictionary[String, Int32]"

.EXAMPLE

PS > New-GenericObject System.Collections.ObjectModel.Collection System.Int32
Creates a simple generic collection

.EXAMPLE

PS > New-GenericObject System.Collections.Generic.Dictionary `
      System.String,System.Int32
Creates a generic dictionary with two types

.EXAMPLE

PS > $secondType = New-GenericObject System.Collections.Generic.List Int32
PS > New-GenericObject System.Collections.Generic.Dictionary `
      System.String,$secondType.GetType()
Creates a generic list as the second type to a generic dictionary

.EXAMPLE

PS > New-GenericObject System.Collections.Generic.LinkedListNode `
      System.String "Hi"
Creates a generic type with a non-default constructor

#>

param(
    ## The generic type to create
    [Parameter(Mandatory = $true)]
    [string] $TypeName,

    ## The types that should be applied to the generic object
    [Parameter(Mandatory = $true)]
    [string[]] $TypeParameters,

    ## Arguments to be passed to the constructor
    [object[]] $ConstructorParameters
)

Set-StrictMode -Version 2

## Create the generic type name
$genericTypeName = $typeName + '`' + $typeParameters.Count
$genericType = [Type] $genericTypeName

if(-not $genericType)
{
    throw "Could not find generic type $genericTypeName"
}

## Bind the type arguments to it
[type[]] $typedParameters = $typeParameters
$closedType = $genericType.MakeGenericType($typedParameters)
if(-not $closedType)
{
    throw "Could not make closed type $genericType"
}

## Create the closed version of the generic type
,[Activator]::CreateInstance($closedType, $constructorParameters)