Using PowerShell Classes

by Jul 5, 2017

Starting with PowerShell 5, you can define classes. They have many use cases. One would be to create libraries of useful helper functions to better organize them. For this, a class would define “static” methods. Here is a simple example:

class HelperStuff
{
   # get first character of string and throw exception
   # when string is empty or multi-line
   static [char] GetFirstCharacter([string]$Text)
   {
      if ($Text.Length -eq 0) { throw 'String is empty' }
      if ($Text.Contains("`n")) { throw 'String contains multiple lines' }
      return $Text[0]
   }
   
   # get file extension in lower case
   static [string] GetFileExtension([string]$Path)
   {
      return [Io.Path]::GetExtension($Path).ToLower()
   }
}

This class “HelperStuff” defines two static methods called “GetFirstCharacter” and “GetFileExtension”. It’s now really easy to find and use this utility functions:

 

PS> [HelperStuff]::GetFirstCharacter('Tobias')
T

PS> [HelperStuff]::GetFileExtension('c:\TEST.TxT') 
.txt

PS> [HelperStuff]::GetFileExtension($profile) 
.ps1

PS>
 

Twitter This Tip! ReTweet this Tip!