PowerShell Classes First Look
A class is a blueprint for objects that groups data and actions together. One blueprint can make many objects that all share the same shape.
Define a class and read a property
The class holds two properties. After making an object, a dot reads one property.
class Book {
[string]$Title
[string]$Author
[string] GetLabel() {
return "$($this.Title) by $($this.Author)"
}
}
$book = [Book]::new()
$book.Title = "Dune"
$book.Author = "Frank Herbert"
$book.TitleCall a method on the object
A method runs code that belongs to the object. GetLabel joins the title and the author.
class Book {
[string]$Title
[string]$Author
[string] GetLabel() {
return "$($this.Title) by $($this.Author)"
}
}
$book = [Book]::new()
$book.Title = "Dune"
$book.Author = "Frank Herbert"
$book.GetLabel()Make an object with New-Object
New-Object is another way to make an object from a class. The object works the same way.
class Book {
[string]$Title
[string]$Author
[string] GetLabel() {
return "$($this.Title) by $($this.Author)"
}
}
$book = New-Object Book
$book.Title = "Dune"
$book.Author = "Frank Herbert"
$book.GetLabel()Example
class Book {
[string]$Title
[string]$Author
[string] GetLabel() {
return "$($this.Title) by $($this.Author)"
}
}
$first = [Book]::new()
$first.Title = "Dune"
$first.Author = "Frank Herbert"
$second = [Book]::new()
$second.Title = "Foundation"
$second.Author = "Isaac Asimov"
$first.GetLabel()
$second.GetLabel()Key points
- Class: A class defines the shape of an object with the class keyword.
- Property: A property holds one piece of data on the object, like a title.
- Method: A method is an action the object can carry out, like building a label.
- New object: Use [Book]::new() to make an object from a class.
- Dot access: Use a dot to read a property or call a method on an object.
In this example, one blueprint makes two separate objects. Each object holds its own title and author, and each GetLabel call builds the label for its own object.
Note
A property type in square brackets, like [string], states what kind of value the property holds.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line makes a new object from the Book class?