In PowerShell, a class
is a template for creating objects.
It defines the properties and methods of the object, and it provides a blueprint for how the object will behave. Cla`sses allow you to create objects that share common properties and behavior, and they allow you to reuse and extend your code.
Here's an example of a class in PowerShell:
class Person {
[string]$FirstName
[string]$LastName
Person([string]$First, [string]$Last) {
$this.FirstName = $First
$this.LastName = $Last
}
[string]ToString() {
return "$($this.FirstName) $($this.LastName)"
}
}
In this example, the Person
class is defined with two properties, FirstName
and LastName
, which are both strings.
The Person
class also has a constructor, which is a special method that is used to initialize the object. The constructor takes two string arguments, $First
and $Last
, which are used to initialize the FirstName
and LastName
properties of the object.
The Person
class also has a ToString()
method, which is a special method that is called when the object is converted to a string. This method returns a string with the FirstName
and LastName
properties concatenated together with a space between them.
To create an object from the Person
class, you can use the New-Object
cmdlet. Here's an example:
$person = New-Object Person -ArgumentList "John", "Doe"
Write-Output $person
In this example, the New-Object
cmdlet is used to create an object from the Person
class.
The -ArgumentList
parameter is used to specify the arguments that will be passed to the constructor, which are "John" and "Doe" in this example. The code will output a string with the FirstName
and LastName
properties concatenated
In PowerShell, a class
is a template for creating objects.
It defines the properties and methods of the object, and it provides a blueprint for how the object will behave. Cla`sses allow you to create objects that share common properties and behavior, and they allow you to reuse and extend your code.
Related tutorials curated for you
How to use -Contains in PowerShell
How to run a .bat file in PowerShell
How to make a directory in PowerShell
How to pause in PowerShell
Everything about certificates in PowerShell
What is Echo in PowerShell?
How to trim text in PowerShell
Using -Or in PowerShell
Piping in PowerShell
How to get the host or computer name in PowerShell
How to list all installed modules in PowerShell
What is PowerShell logging?