Creating a class
A class is used to describe an object. This may be any object, which means that a class in PowerShell might be used for any purpose.
Classes in PowerShell are created using the class
keyword. The following class contains a single property:
class MyClass {
[string]$Value = 'My value'
}
You can create the class by using either the New-Object
command or the ::new()
method:
PS> New-Object MyClass
Value
-----
My value
PS> [MyClass]::new()
Value
-----
My Value
This example creates an instance of the class and displays the property that was defined for the class.
Properties
The properties defined in a class may define a .NET type and may have a default value if required. The following class has a single property with the String
type:
class MyClass {
[string]$Value = 'My value'
}
PowerShell automatically adds hidden get
and set
methods used to access the property; these cannot be overridden or changed...