PowerShell classes

PowerShell V5 introduced a new feature called a PowerShell class. If you are familiar with programming in any language, you will recognize this new feature. If not, don't worry about it too much as you can get pretty far with some basic programming knowledge that you already learned using PowerShell. This is the one of the original design goals in Jeffrey Snover's Monad manifesto-to create PowerShell as a gateway step to C# for those so inclined.

Since you're already adept at using PowerShell, you know that anything and everything PowerShell operates on and produces is a class, specifically a class in the .NET Framework. Run Get-Process, and you get a collection of the System.Diagnostics.Process objects.

We won't get too far into discussing classes here, as that is a subject on which many books have already been written. For our purposes, think of a class as a grouping of properties and functions inside one place that can be created to perform specific functions. PowerShell classes are designed to provide similar functionality.

PowerShell classes are very similar to PowerShell functions (a design that is not by accident), so they are easy to understand once you grasp some simple concepts. Let's use a common example—a class that defines a point, something that represents a location on the computer screen. We would need to describe this point's location using x and y coordinates and also have some way to adjust those coordinates to move the point to a new location. This is accomplished in a PowerShell class, as follows:

powershell
class Point
{
$X = 0
$Y = 0
[void] Move($xOffset, $yOffset)
{
$this.X += $xOffset
$this.Y += $yOffset
}
}

Not too scary, right? It looks like a PowerShell function for the most part. We declare properties with normal PowerShell variable syntax and declare the class method using the PowerShell function syntax. We can create a point object and move it, as follows:

powershell
$point = [Point]::new()
$point.Move(10, 20)
$point

Again, this book can't begin to cover the programming concepts you would need in order to get started. It is enough to describe the concepts we are going to use with DSC resources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset