Classes in PowerShell v5 Scripts

PowerShell is a Microsoft scripting language used primarily by IT guys. I recently downloaded the pre-release version of PowerShell v5. It’s part of the Windows Management Framework v5. As a developer, the one new feature in v5 I was most interested in is the ability to create a class (data and functions) in a PowerShell script.

Update note: I was using the September 2014 Preview and discovered that there’s still quite of bit of work to be done on PowerShell classes. In particular, class methods cannot return arrays yet. The PowerShell team says that feature should be added in the November 2014 release.

Update: The November 2014 preview was released on Nov. 18 and that version does now support methods that return an array.


Here’s the code for a quick demo:

write-host "`nBegin demo of PowerShell v5 classes"

class Person {

 [void] SetLast([string]$ln)
  $lastName = $ln

 [string] ToString()
  return $firstName + " " + $lastName

write-host "`nCreating Person object Thomas Smith"
[Person]$p = [Person]::new()
$p.lastName = "Smith"
$p.firstName = "Thomas"

write-host "`nLast name is: "
write-host $p.lastName

write-host "`nChanging last name to 'Law'"

write-host "`nPerson full name is: "
[string]$fullName = $p.ToString()
write-host $fullName

write-host "`nEnd demo"

The demo script defines a class named Person. The class has two data members, lastName and firstName. The class is created with:

[Person]$p = [Person]::new()

Class method SetLast can give a value to the last name like so:


Because class data is fully accessible, giving or changing the last name could also have been done directly by:

$p.lastName = “Law”

Anyway, the ability to use program-defined classes in a PowerShell v5 script is a very nice addition to the language. I intend to see if I can refactor some of my C# machine learning code to PowerShell.

This entry was posted in Machine Learning. Bookmark the permalink.