Creating a class
Classes were first introduced in Chapter 7, Working with .NET. A class was described as the recipe used to define a type; it 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 describes a type that contains a single property:
class MyClass {
[string] $Value = 'My value'
}
An instance of a type (defined by a class) can be explicitly created by using either the New-Object
command or the ::new()
method:
PS> New-Object MyClass
Value
-----
My Value
PS> [MyClass]::new()
Value
-----
My Value
The type can also be implicitly created by casting a dictionary. For example, a hashtable is used below:
# Do not change any default property values
[MyClass]@{}
# Or set a new value for the Value property
[MyClass]@{ Value = 'New value' }
It is also possible to create instances...