Creating .NET objects in PowerShell is fairly straightforward using the New-Object cmdlet, but eventually you might have a situation where you need to create an instance of a nested class which is less obvious. Fortunately, PowerShell 3.0 includes some improvements that makes this possible.
Creating an Instance of a Nested Class
public class Turkey
{
public Turkey() { }
public virtual void GetDetails()
{
Console.WriteLine("Age: {0}", this.Age);
Console.WriteLine("Breed: {0}", this.Breed);
}
public string Breed
{
get;
set;
}
public int Age
{
get;
set;
}
///
/// A Wild Turkey is a nested subclass of Turkey
///
public class WildTurkey : Turkey
{
public WildTurkey() { }
public override void GetDetails()
{
base.GetDetails();
Console.WriteLine("Region: {0}", this.Region);
}
public string Region
{
get;
set;
}
}
}
#
# Create a new Turkey Object
#
$turkey = New-Object -TypeName TurkeyTrackerApp.Turkey
#
# List Properties
#
$turkey | Get-Member -Type Properties
TypeName: TurkeyTrackerApp.Turkey
Name MemberType Definition
---- ---------- ----------
Age Property int Age {get;set;}
Breed Property string Breed {get;set;}
#
# Create a new Wild Turkey Object
#
$wildTurkey = New-Object -TypeName TurkeyTrackerApp.Turkey+WildTurkey
#
# List Properties
#
$wildTurkey | Get-Member -Type Properties
TypeName: TurkeyTrackerApp.Turkey+WildTurkey
Name MemberType Definition
---- ---------- ----------
Age Property int Age {get;set;}
Breed Property string Breed {get;set;}
Region Property string Region {get;set;}
# Load the TurkeyTrackerApp assembly
Add-Type -Path "G:\Assemblies\TurkeyTrackerApp.dll"