FredBainbridge

PowerShell v5 has class!

PowerShell version 5.0 added the ability to use the class designator in scripts. Don Jones has a good write up on it. This allows for live .NET framework class creation. This is a REALLY nice feature. There were a few ways to create custom objects in PowerShell before this, including specifying c# code directly in the script, using add-member and other ways. These all worked fine, but each has rather annoying limitations or overhead.

Example –

class Beer {
   [string] $Name
   [ValidateSet("IPA","LAGER","STOUT")] 
   [string] $Type
    
   Beer($NameIn, $TypeIn)
   {
       $this.Name = $NameIn
       $this.Type = $TypeIn 
    }   
} 

Usage:

$beer = [Beer]::new("Brew","IPA")
#OR
$beer = new-object Beer("Brew","IPA")

You can use all the normal function parameters with this class.


Share