Creating Real Classes

by Sep 11, 2015

PowerShell introduces class support in PowerShell 5.0, but you can define your own classes in other PowerShell versions as well. Simply use C# code to define true classes, then compile these classes using Add-Type.

Here is a sample that creates a new class called "myClass" with three properties. PowerShell can then instantiate objects by using New-Object.

$code = '
    using System;
    public class myClass
    {
        public bool Enabled { get; set; }
        public string Name { get; set; }
        public DateTime Time { get; set; }


    }

'

Add-Type -TypeDefinition $code
$instance = New-Object -TypeName myClass
$instance.Enabled = $true
$instance.Time = Get-Date
$instance.Name = $env:username
$instance

Why would you do this? Your classes could consolidate information retrieved from multiple sources, and you would have all the sophisticated features found in C# to define your class, including methods, dynamic and static members, and more.

Obviously, this technique is probably most exciting for users with some developer background.

Twitter This Tip! ReTweet this Tip!