Generating New-Object Wrapper Functions for an Assembly

One of the best parts of being a Microsoft MVP is having conversations with all the other, really bright MVPs.  The PowerShell team just recently added Doug Finke as an MVP – congratulations Doug!  It isn’t too uncommon for the PowerShell MVPs to challenge and push one another.  It is a great learning experience!

Over the weekend, Doug and I engaged in one of these and in the end we came up with a little bit of PowerShell script (V2 required for the generics support) that can automatically generate wrapper functions around the constructors of public .NET types in an assembly.  These wrapper functions are strongly typed (well mostly) and support generic types.  Here’s the script:

Set-StrictMode -Version Latest

[Reflection.Assembly]::LoadWithPartialName($assemblyName).GetExportedTypes() |
% {
    $fname = $_.FullName
    $typeArgs  = @($_.GetGenericArguments() | %{"`$Of" + $_.Name})
    $typeDecls = @($_.GetGenericArguments() | %{"[string]`$Of" + $_.Name})
    $_.GetConstructors(‘Instance,Public’) |
    % {
        $paramArgs  = @($_.GetParameters() | %{"`$" + $_.Name})
        $paramDecls = @($_.GetParameters() | 
            %{"$(if (!$_.ParameterType.ContainsGenericParameters) {"[$($_.ParameterType)]"})`$$($_.Name)"})
        if ("$paramDecls" -notmatch ‘\*’) {
            $OFS = ‘,’
            if ($typeArgs.Length -gt 0) {
                $genFname = $fname.Substring(0, $fname.LastIndexOf(‘`’))
                $decls = $typeDecls + $paramDecls
function New-$($genFname.Replace(‘.’,”)) {
    New-Object `"$genFname$("`[$typeArgs`]")`" $paramArgs

            else {
function New-$($fname.Replace(‘.’,”)) {
    New-Object `"$fname`" $paramArgs

NOTE: if you copy/paste this script, watch out for whitespace after the here strings’ opening sequence – @” – there shouldn’t be any. 

If you run it on mscorlib, it will product wrapper functions like so:

function New-SystemGuid {
    New-Object "System.Guid" $a,$b,$c,$d

function New-SystemCollectionsGenericDictionary {
    New-Object "System.Collections.Generic.Dictionary[$OfTKey,$OfTValue]"

function New-SystemCollectionsGenericList {
    New-Object "System.Collections.Generic.List[$OfT]"

Then you can create a generic list like so:

PS> $list = New-SystemCollectionsGeneicList –OfT double
PS> $list.add(1.1)
PS> $list.add("two")
Cannot convert argument "0", with value: "two", for "add" to type "System.Double"

This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s