Skip to main content

Use the -TypeDefinition parameter of the Add-Type class to define a new .NET class or extend an existing one within a PowerShell script.

#############################################################################
##
## Invoke-AddTypeTypeDefinition
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

    Demonstrates the use of the -TypeDefinition parameter of the Add-Type
    cmdlet.

#>

Set-StrictMode -Version 3

## Define the new C# class
$newType = @'
using System;

namespace PowerShellCookbook
{
    public class AddTypeTypeDefinitionDemo
    {
        public string SayHello(string name)
        {
            var result = string.Format("Hello {0}.", name);
            return result;
        }
    }
}
'@

## Add it to the Powershell session
Add-Type -TypeDefinition $newType

## Show that we can access it like any other .NET type
$greeter = New-Object PowerShellCookbook.AddTypeTypeDefinitionDemo
$greeter.SayHello("World")