PowerShell Classes: Getting Started

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

PowerShell is an open-source scripting language designed for system administration. It’s powerful and flexible, but there are a few key concepts you need to know before getting started with PowerShell classes.

The “powershell 7 classes” is a class that allows users to create and manage PowerShell scripts. The class includes everything from the basics, such as creating variables, to more advanced topics like running commands on remote computers.

PowerShell Classes: Getting Started

PowerShell is a scripting language that is object-oriented. Objects are what you see on your screen when you execute commands and view the outcome. Objects aren’t created out of thin air; they’re created by developers, who use classes to instantiate them. The definitions or schemas of those objects are represented by PowerShell classes.

These aren’t “new” objects, despite the fact that you may be acquainted with commands like New-Object and the pscustomobject type accelerator. The objects created by these methods are of a specified kind. The type is defined by PowerShell classes.

You’ll learn how to get started with PowerShell classes in this lesson. You’ll use constructors to build your first class, then learn how to generate objects from it and decorate it with attributes and methods.

Check out the blog article Back to Basics: Understanding PowerShell Objects for more information on concepts like objects, properties, and methods.

Prerequisites

Making Your First Object and Class

You should go through establishing a basic class before learning the ins and outs of a PowerShell class. The more sophisticated subjects will be covered later.

It will feel similar to defining a function when you create your first class. The core syntax is the same in both languages. A class, like a function, is constructed from a definition. However, unlike functions, the first line does not begin with function and then the name of the function; instead, it begins with class and then the name of your object type.

Associated: PowerShell Functions: A Beginner’s Guide

The skeleton of a class named student is shown below.

Classes contain parameters-like properties that are characteristics that characterize the class. The following example demonstrates a student class with two properties: FirstName and LastName.

When you establish a property, you should always declare a type that specifies a “schema” for what values the property may contain. Both attributes are specified as strings in the example below.

Property types should always be defined. You’ll understand why afterwards.

[string] student class [string] $FirstName $LastName $LastName $LastName $LastName $

Create or instantiate an object from a class once you’ve defined it. There are many methods to create objects from classes; one typical option is to use type accelerators to express the class, such as [student], followed by a default method called new that comes with every class ().

Using the type accelerator shortcut is the same as using the New-Object command to create an object.

student New-Object -TypeName

Assign values to attributes once you’ve generated an object from that class. The values Tyler and Muir are assigned to the FirstName and LastName attributes in the example below.

[string] student class [string] $FirstName $LastName $LastName $LastName $LastName $ $student1 = [student]::new() $student1.FirstName = ‘Tyler’ $student1.LastName = ‘Muir’ $student1

After you’ve created the object and provided values to its attributes, you may examine it by calling the variable to which it was assigned, as shown below.

Using the student class to create an object.Using the student class to create an object.

Now that you’ve built an object from a class, you may examine it using the Get-Member cmdlet, just like any other object in PowerShell. The object kept under the $student1 variable is of type student, as seen below.

The object type will always be associated with the class name.

Get-Member gives four methods and two properties, as you can see. The qualities are certainly recognizable, but the techniques aren’t. PowerShell comes with certain methods pre-installed, but you may add your own or change the defaults.

Members of the custom student object are shown.Members of the custom student object are shown.

Methods Development

You can see a few default methods on the object in the example above, but you’ll probably want to develop your own. To do so, you’ll need to include one or more methods in the class declaration.

A method definition looks like this, with an output type that specifies the kind of object that will be returned from the method, the method’s name, and the code to run within a scriptblock.

[<output type>]<name>() { <code that runs when the method is executed> }

Take note of the parenthesis () after the name. This is where method parameters are defined (covered later). Method parameters, like function parameters, enable you to modify the functionality of a method.

Method scriptblocks should seem familiar if you’ve written and run PowerShell functions before, but there are a few particular restrictions for methods that you should be aware of.

return is required

Objects may be returned by simply inserting them anywhere in a PowerShell function, as seen in the example below.

$object = Get-Service $object = Get-Service $object = Get-Service $object = Get-Service $object = Get- ## $object Sending the item to the pipeline is all that is required.

If a method returns an object, unlike functions, you must use the return construct, as seen below.

return ‘foo’ from [string]GetName()

Using the variable $this

Another distinction between methods and functions is the $this variable. The $this variable refers to the current object’s properties or other methods when declared within a method.

The student class has a method named GetName() that concatenates the values of the FirstName and LastName fields and returns them.

[string]$FirstName [string]$Student[string]$Student[string]$Student[string]$Stud $LastName [string]GetName() return “$($this.FirstName) $($this.LastName)” $LastName [string]GetName() return “$($this.FirstName) $($this.LastName)”

You may now use dot notation to use the GetName() function, as demonstrated below. GetName() will return the values you previously supplied to FirstName and LastName.

Creating a class with a method and displaying it on the screen.Creating a class with a method and displaying it on the screen.

Incorporating Parameters into Methods

When you executed the line $student1.GetName() in the previous example, you were using the GetName() function as-is. You can specify arguments within parenthesis the same way you may construct functions.

The GetName() function simply returned the values for the FirstName and LastName fields that were set. But what if you wanted a function to set attributes that GetName() could later retrieve? In such situation, method parameters must be defined.

Define method parameters by including one or more parameters in the method parameter parenthesis, separated by a comma, as illustrated below.

The [void] output type should be noted. When a function doesn’t return anything, there’s no need for a return construct, and the output type should be [void] to notify PowerShell the method doesn’t return anything.

[void] $Name = SetName([string]$Name)

Perhaps the SetName() function allows a whole name as an argument (first and last name). If that’s the case, you may divide the string in the scriptblock and assign the first and last names that way.

Here’s what it looks like now that the SetName() method has been added to the student class.

student in class [string] ‘ [string] $FirstName [string] $LastName return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)$this.LastName = ($Name -split”)$this.LastName = ($Name -split”)$

The SetName() function now accepts a whole name as an argument, which sets the current object’s FirstName and LastName fields.

Making a class with a void method and displaying the output once it has been executed.Making a class with a void method and displaying the output once it has been executed.

Methods of Overloading

You may want to establish many parameter sets for a method. You may establish alternative parameter “contexts” or method signatures, similar to how parameter sets operate in functions and cmdlets.

You might use the SetName() method to set the FirstName and LastName parameters by giving a whole name or the first and last names individually. You don’t have to pick; method signatures allow you to specify both.

Overloading occurs when you create many method signatures in a single class.

Using the preceding section as an example, you can construct an overload for the SetName() function that accepts two strings instead of one. The SetName() function thinks the first string is the FirstName and the second string is the LastName when you give in two strings instead of one. The class would look like this with that overload.

class student [string]$FirstName [string]$LastName [string]GetName() return “$($this.FirstName) $($this.LastName)” [void]SetName([string]$Name) $this.FirstName = ($Name -split”)[0] $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -spli

Using one or two strings to demonstrate how the method overload works.Using one or two strings to demonstrate how the method overload works.

Constructors of Classes

You may instruct PowerShell to execute some user-defined code called a constructor whenever you create an object using the new() function or another method. Constructors are similar to methods, except they are executed automatically by PowerShell when an object is created.

A default constructor exists for every class. This default constructor isn’t really useful; it’s just responsible for instantiating the object. By looking at the output of the New method, you can see the default constructor. This line returns a single new() function, as seen below.

Default constructor in PowerShellDefault constructor in PowerShell

Overloading of the Constructor

You may want to specify a value for the FirstName and LastName attributes as soon as the object is created, rather than using the standard dot syntax. In such instance, you may write a constructor that takes an argument and calls SetName ().

A constructor for the student class is shown below. It’s worth noting that the constructor has no name or isn’t preceded by an output type. The name of the constructor is always the same as the class name.

We can reuse the function we previously built to handle setting the variables by calling an existing method in the constructor.

$this.SetName($Name) student([string]$Name)

That constructor has now been added to the student class, as seen below.

class student { [string]$FirstName [string]$LastName $this.SetName($Name) student([string]$Name) [string]GetName() { return “$($this.FirstName) $($this.LastName)” } [void]SetName([string]$Name) { $this.FirstName = ($Name -split ‘ ‘)[0] $this.LastName = ($Name -split ‘ ‘)[1] } [void]SetName([string]$FirstName,[string]$LastName) { $this.FirstName = $FirstName $this.LastName = $LastName } }

When you create a new student object and include a string argument, the object attributes are set to the anticipated values right away.

Using the constructor with a string to show the resultUsing the constructor with a string to show the result

With [student]::, you can see the constructor is overworked once again. New. Now you’ll see that the new constructor is overworked has a Name argument.

constructor is overworkedconstructor is overworked

Defining a Default and constructor is overworked

Now that you have an constructor is overworked on your student class, PowerShell overwrites the default constructor. But, you can get it back by manually creating one without parameters.

In the student class below, you can see what it looks like.

class student { [string]$FirstName [string]$LastName $this.SetName($Name) student([string]$Name) student() {} [void]SetName([string]$Name) { $this.FirstName = ($Name -split ‘ ‘)[0] $this.LastName = ($Name -split ‘ ‘)[1] } }

Check the constructors once again. Both constructors should now appear.

Creating both a standard and a custom constructorCreating both a standard and a custom constructor

Inheritance by Class

PowerShell classes may be built hierarchically with many classes, much like any other object-oriented language. Each class may have “parent” and “child” classes that start with more general, less particular goals and work their way up to more specific ones.

Our student class, for example, represents a university student (child/specific). That university student (parent/generic) is a person. These two ideas are intertwined and create a pyramid.

A child class may inherit a parent class, which implies it can hold all of the parent class’s properties and methods (members). We know that a human class may contain eye color, height, and weight attributes, as well as a method named SetHeight ().

If a student is a person, that student still has those properties and methods. It would duplicate effort to implement those same members on the student class that the person class already has. You can define Inheritance by Class to automatically define all members of the person class on the student class.

If this doesn’t make sense right now, it will when we go through the demonstration.

Inheritance by Class Demo

Make a clone of the student class you just created, delete the constructors, and rename it to person. The following lesson should appeal to your individual class.

A student, of course, has a first and last name, but designating the class as a person allows it to be described more properly. You may develop more particular “child” classes from a more “generic” class like this one.

a person of distinction $FirstName$LastName$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$ return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName

Create a handful of classes that each represent a person with a distinct role. You now have a teacher and a pupil class in the code sample below, for example.

[int]$EmployeeId class instructor [int]$StudentId class student

The instructor and student classes are mutually exclusive from the person class in their current state. They are unrelated, yet they are unable to inherit any members of the person class. Let’s make a difference.

Define the hierarchy by making the instructor and student classes “child” classes of the person class, which inherits. As seen below, you may declare inheritance by putting a colon (:) after the class name and then the name of the parent class.

person [int]$EmployeeId class instructor person [int]$StudentId class student

This is how your complete class script should now look:

a person of distinction $FirstName$LastName$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$ return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName person [int]$EmployeeId class instructor person [int]$StudentId class student

When you instantiate a teacher or student object at this point, both classes will have the same members as the person class.

Inheritance by Class DemoInheritance by Class Demo

Using Constructors to Inherit

As you saw above, class methods are inherited via Inheritance by Class. This behavior may lead you to think that constructors would follow that same logic, but you’d be wrong. Constructors are not inherited, and constructors for all child classes must be defined in each child class separately.

For example, perhaps you just defined an constructor is overworked for the person class but didn’t define a constructor for the teacher class, as shown below.

[string]hidden class person $FirstName [string]$LastName [string]$FirstName [string]$LastName [string]$LastName [string return “$($this.FirstName) $($this.LastName)” GetName() [void] SetName([string]$Name) $this.FirstName = ($Name -split”)[0] $this.LastName = ($Name -split”) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName $this.SetName($Name) person([string]$Name)

Then, as illustrated below, you construct a child class, such as teacher, and attempt to generate an object with no parameters from it. Because a parameterless constructor was not specified within the instructor class, PowerShell produces an error.

There is no class declared for the child class.There is no class declared for the child class.

If you’re merely using a child class as a template, you don’t need a constructor. You may also add constructors if you wish to utilize the parent class as a standalone class as well as a parent class. However, you must ensure that the constructors in the parent class match those in the child classes.

Attributes of Class Members

Classes, like command parameters in PowerShell, may contain member attributes. Each member’s conduct is influenced by these traits.

Members Who Aren’t Visible

If you’re just utilizing a class member for internal reasons and don’t want the user to be able to read or write to it, you may hide it. You may, for example, have a method that is only utilized by other methods. There’s no need to make that way available to the user.

Use the hidden property to define a hidden member, as demonstrated below.

class instructor $EmployeeId $EmployeeId $EmployeeId $EmployeeId $EmployeeId $E

That property is no longer visible when using Get-Member to view all object members.

Attributes of Class MembersAttributes of Class Members

Setting a class member to hidden conceals it from display but does not prevent access to the value. To save sensitive data, you should not conceal properties.

Members Who Remain Static

Remember that the word “instantiate” was used previously in this course to indicate constructing an object from a class. When you instantiate an object, it inherits all of the attributes and methods defined by the class. However, this isn’t always the case.

Sometimes the overhead of instantiating a complete object is unnecessary. Instead, you’ll need to rapidly refer to a single class member. You may make a class member static in such situation.

As with the hidden property, use the static keyword to make a class member static, as seen below.

$MaxClassCount = 7 class student [int]static

Unlike typical class members, PowerShell does not create properties and methods from static class members. When you define a class member as static, like Members Who Aren’t Visible, it doesn’t show up when you use Get-Member.

Members Who Remain StaticMembers Who Remain Static

For example, you could want to correlate university class titles with student courses and limit the number of university classes that a student can take. Create a Classes array member and a MaxClassCount member to do this.

Because the MaxClassCount member is seldom changed by the user, you decide to make it static.

Finally, an AddClass() function is created to add a class to the student’s schedule, but only if the number of classes is fewer than the MaxClassCount.

[string[]] student class $Classes = @() [int]static $MaxClassCount = 7 [void] $Classes = @() [int]static $Classes = @() [int]static $Classes AddClass ($Name) ([string]$Name) ([string]$Name) ([string]$Name $this.Classes += $Name if ($this.Classes.Count -lt [student]::MaxClassCount)

If you try to create a new student object with too many university courses assigned to it, PowerShell will only assign the maximum amount, which is seven.

$student1 = [student]::new() ‘PE’,’English’,’Math’,’History’,’Computer Science’,’French’,’Wood Working’,’Cooking’ | ForEach-Object $student1.AddClass(

PowerShell is a scripting language that is object-oriented. Objects are what you see on your screen when you execute commands and view the outcome. Objects aren’t created out of thin air; they’re created by developers, who use classes to instantiate them. The definitions or schemas of those objects are represented by PowerShell classes.

These aren’t “new” objects, despite the fact that you may be acquainted with commands like New-Object and the pscustomobject type accelerator. The objects created by these methods are of a specified kind. The type is defined by PowerShell classes.

You’ll learn how to get started with PowerShell classes in this lesson. You’ll use constructors to build your first class, then learn how to generate objects from it and decorate it with attributes and methods.

Check out the blog article Back to Basics: Understanding PowerShell Objects for more information on concepts like objects, properties, and methods.

Prerequisites

Making Your First Object and Class

You should go through establishing a basic class before learning the ins and outs of a PowerShell class. The more sophisticated subjects will be covered later.

It will feel similar to defining a function when you create your first class. The core syntax is the same in both languages. A class, like a function, is constructed from a definition. However, unlike functions, the first line does not begin with function and then the name of the function; instead, it begins with class and then the name of your object type.

Associated: PowerShell Functions: A Beginner’s Guide

The skeleton of a class named student is shown below.

Classes contain parameters-like properties that are characteristics that characterize the class. The following example demonstrates a student class with two properties: FirstName and LastName.

When you establish a property, you should always declare a type that specifies a “schema” for what values the property may contain. Both attributes are specified as strings in the example below.

Property types should always be defined. You’ll understand why afterwards.

[string] student class [string] $FirstName $LastName $LastName $LastName $LastName $

Create or instantiate an object from a class once you’ve defined it. There are many methods to create objects from classes; one typical option is to use type accelerators to express the class, such as [student], followed by a default method called new that comes with every class ().

Using the type accelerator shortcut is the same as using the New-Object command to create an object.

student New-Object -TypeName

Assign values to attributes once you’ve generated an object from that class. The values Tyler and Muir are assigned to the FirstName and LastName attributes in the example below.

[string] student class [string] $FirstName $LastName $LastName $LastName $LastName $ $student1 = [student]::new() $student1.FirstName = ‘Tyler’ $student1.LastName = ‘Muir’ $student1

After you’ve created the object and provided values to its attributes, you may examine it by calling the variable to which it was assigned, as shown below.

Using the student class to create an object.Using the student class to create an object.

Now that you’ve built an object from a class, you may examine it using the Get-Member cmdlet, just like any other object in PowerShell. The object kept under the $student1 variable is of type student, as seen below.

The object type will always be associated with the class name.

Get-Member gives four methods and two properties, as you can see. The qualities are certainly recognizable, but the techniques aren’t. PowerShell comes with certain methods pre-installed, but you may add your own or change the defaults.

Members of the custom student object are shown.Members of the custom student object are shown.

Methods Development

You can see a few default methods on the object in the example above, but you’ll probably want to develop your own. To do so, you’ll need to include one or more methods in the class declaration.

A method definition looks like this, with an output type that specifies the kind of object that will be returned from the method, the method’s name, and the code to run within a scriptblock.

[<output type>]<name>() { <code that runs when the method is executed> }

Take note of the parenthesis () after the name. This is where method parameters are defined (covered later). Method parameters, like function parameters, enable you to modify the functionality of a method.

Method scriptblocks should seem familiar if you’ve written and run PowerShell functions before, but there are a few particular restrictions for methods that you should be aware of.

return is required

Objects may be returned by simply inserting them anywhere in a PowerShell function, as seen in the example below.

$object = Get-Service $object = Get-Service $object = Get-Service $object = Get-Service $object = Get- ## $object Sending the item to the pipeline is all that is required.

If a method returns an object, unlike functions, you must use the return construct, as seen below.

return ‘foo’ from [string]GetName()

Using the variable $this

Another distinction between methods and functions is the $this variable. The $this variable refers to the current object’s properties or other methods when declared within a method.

The student class has a method named GetName() that concatenates the values of the FirstName and LastName fields and returns them.

[string]$FirstName [string]$Student[string]$Student[string]$Student[string]$Stud $LastName [string]GetName() return “$($this.FirstName) $($this.LastName)” $LastName [string]GetName() return “$($this.FirstName) $($this.LastName)”

You may now use dot notation to use the GetName() function, as demonstrated below. GetName() will return the values you previously supplied to FirstName and LastName.

Creating a class with a method and displaying it on the screen.Creating a class with a method and displaying it on the screen.

Incorporating Parameters into Methods

When you executed the line $student1.GetName() in the previous example, you were using the GetName() function as-is. You can specify arguments within parenthesis the same way you may construct functions.

The GetName() function simply returned the values for the FirstName and LastName fields that were set. But what if you wanted a function to set attributes that GetName() could later retrieve? In such situation, method parameters must be defined.

Define method parameters by including one or more parameters in the method parameter parenthesis, separated by a comma, as illustrated below.

The [void] output type should be noted. When a function doesn’t return anything, there’s no need for a return construct, and the output type should be [void] to notify PowerShell the method doesn’t return anything.

[void] $Name = SetName([string]$Name)

Perhaps the SetName() function allows a whole name as an argument (first and last name). If that’s the case, you may divide the string in the scriptblock and assign the first and last names that way.

Here’s what it looks like now that the SetName() method has been added to the student class.

student in class [string] ‘ [string] $FirstName [string] $LastName return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)$this.LastName = ($Name -split”)$this.LastName = ($Name -split”)$

The SetName() function now accepts a whole name as an argument, which sets the current object’s FirstName and LastName fields.

Making a class with a void method and displaying the output once it has been executed.Making a class with a void method and displaying the output once it has been executed.

Methods of Overloading

You may want to establish many parameter sets for a method. You may establish alternative parameter “contexts” or method signatures, similar to how parameter sets operate in functions and cmdlets.

You might use the SetName() method to set the FirstName and LastName parameters by giving a whole name or the first and last names individually. You don’t have to pick; method signatures allow you to specify both.

Overloading occurs when you create many method signatures in a single class.

Using the preceding section as an example, you can construct an overload for the SetName() function that accepts two strings instead of one. The SetName() function thinks the first string is the FirstName and the second string is the LastName when you give in two strings instead of one. The class would look like this with that overload.

class student [string]$FirstName [string]$LastName [string]GetName() return “$($this.FirstName) $($this.LastName)” [void]SetName([string]$Name) $this.FirstName = ($Name -split”)[0] $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -spli

Using one or two strings to demonstrate how the method overload works.Using one or two strings to demonstrate how the method overload works.

Constructors of Classes

You may instruct PowerShell to execute some user-defined code called a constructor whenever you create an object using the new() function or another method. Constructors are similar to methods, except they are executed automatically by PowerShell when an object is created.

A default constructor exists for every class. This default constructor isn’t really useful; it’s just responsible for instantiating the object. By looking at the output of the New method, you can see the default constructor. This line returns a single new() function, as seen below.

Default constructor in PowerShellDefault constructor in PowerShell

Overloading of the Constructor

You may want to specify a value for the FirstName and LastName attributes as soon as the object is created, rather than using the standard dot syntax. In such instance, you may write a constructor that takes an argument and calls SetName ().

A constructor for the student class is shown below. It’s worth noting that the constructor has no name or isn’t preceded by an output type. The name of the constructor is always the same as the class name.

We can reuse the function we previously built to handle setting the variables by calling an existing method in the constructor.

$this.SetName($Name) student([string]$Name)

That constructor has now been added to the student class, as seen below.

class student { [string]$FirstName [string]$LastName $this.SetName($Name) student([string]$Name) [string]GetName() { return “$($this.FirstName) $($this.LastName)” } [void]SetName([string]$Name) { $this.FirstName = ($Name -split ‘ ‘)[0] $this.LastName = ($Name -split ‘ ‘)[1] } [void]SetName([string]$FirstName,[string]$LastName) { $this.FirstName = $FirstName $this.LastName = $LastName } }

When you create a new student object and include a string argument, the object attributes are set to the anticipated values right away.

Using the constructor with a string to show the resultUsing the constructor with a string to show the result

With [student]::, you can see the constructor is overworked once again. New. Now you’ll see that the new constructor is overworked has a Name argument.

constructor is overworkedconstructor is overworked

Defining a Default and constructor is overworked

Now that you have an constructor is overworked on your student class, PowerShell overwrites the default constructor. But, you can get it back by manually creating one without parameters.

In the student class below, you can see what it looks like.

class student { [string]$FirstName [string]$LastName $this.SetName($Name) student([string]$Name) student() {} [void]SetName([string]$Name) { $this.FirstName = ($Name -split ‘ ‘)[0] $this.LastName = ($Name -split ‘ ‘)[1] } }

Check the constructors once again. Both constructors should now appear.

Creating both a standard and a custom constructorCreating both a standard and a custom constructor

Inheritance by Class

PowerShell classes may be built hierarchically with many classes, much like any other object-oriented language. Each class may have “parent” and “child” classes that start with more general, less particular goals and work their way up to more specific ones.

Our student class, for example, represents a university student (child/specific). That university student (parent/generic) is a person. These two ideas are intertwined and create a pyramid.

A child class may inherit a parent class, which implies it can hold all of the parent class’s properties and methods (members). We know that a human class may contain eye color, height, and weight attributes, as well as a method named SetHeight ().

If a student is a person, that student still has those properties and methods. It would duplicate effort to implement those same members on the student class that the person class already has. You can define Inheritance by Class to automatically define all members of the person class on the student class.

If this doesn’t make sense right now, it will when we go through the demonstration.

Inheritance by Class Demo

Make a clone of the student class you just created, delete the constructors, and rename it to person. The following lesson should appeal to your individual class.

A student, of course, has a first and last name, but designating the class as a person allows it to be described more properly. You may develop more particular “child” classes from a more “generic” class like this one.

a person of distinction $FirstName$LastName$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$ return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName

Create a handful of classes that each represent a person with a distinct role. You now have a teacher and a pupil class in the code sample below, for example.

[int]$EmployeeId class instructor [int]$StudentId class student

The instructor and student classes are mutually exclusive from the person class in their current state. They are unrelated, yet they are unable to inherit any members of the person class. Let’s make a difference.

Define the hierarchy by making the instructor and student classes “child” classes of the person class, which inherits. As seen below, you may declare inheritance by putting a colon (:) after the class name and then the name of the parent class.

person [int]$EmployeeId class instructor person [int]$StudentId class student

This is how your complete class script should now look:

a person of distinction $FirstName$LastName$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$[string]$ return “$($this.FirstName) $($this.LastName)” GetName() [void] $this.FirstName = ($Name -split”)[0] SetName([string]$Name) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName person [int]$EmployeeId class instructor person [int]$StudentId class student

When you instantiate a teacher or student object at this point, both classes will have the same members as the person class.

Inheritance by Class DemoInheritance by Class Demo

Using Constructors to Inherit

As you saw above, class methods are inherited via Inheritance by Class. This behavior may lead you to think that constructors would follow that same logic, but you’d be wrong. Constructors are not inherited, and constructors for all child classes must be defined in each child class separately.

For example, perhaps you just defined an constructor is overworked for the person class but didn’t define a constructor for the teacher class, as shown below.

[string]hidden class person $FirstName [string]$LastName [string]$FirstName [string]$LastName [string]$LastName [string return “$($this.FirstName) $($this.LastName)” GetName() [void] SetName([string]$Name) $this.FirstName = ($Name -split”)[0] $this.LastName = ($Name -split”) $this.LastName = ($Name -split”)[1] $this.LastName = ($Name -split”) [void] $this.FirstName = $FirstName SetName([string]$FirstName,[string]$LastName) $LastName = $this.LastName $this.SetName($Name) person([string]$Name)

Then, as illustrated below, you construct a child class, such as teacher, and attempt to generate an object with no parameters from it. Because a parameterless constructor was not specified within the instructor class, PowerShell produces an error.

There is no class declared for the child class.There is no class declared for the child class.

If you’re merely using a child class as a template, you don’t need a constructor. You may also add constructors if you wish to utilize the parent class as a standalone class as well as a parent class. However, you must ensure that the constructors in the parent class match those in the child classes.

Attributes of Class Members

Classes, like command parameters in PowerShell, may contain member attributes. Each member’s conduct is influenced by these traits.

Members Who Aren’t Visible

If you’re just utilizing a class member for internal reasons and don’t want the user to be able to read or write to it, you may hide it. You may, for example, have a method that is only utilized by other methods. There’s no need to make that way available to the user.

Use the hidden property to define a hidden member, as demonstrated below.

class instructor $EmployeeId $EmployeeId $EmployeeId $EmployeeId $EmployeeId $E

That property is no longer visible when using Get-Member to view all object members.

Attributes of Class MembersAttributes of Class Members

Setting a class member to hidden conceals it from display but does not prevent access to the value. To save sensitive data, you should not conceal properties.

Members Who Remain Static

Remember that the word “instantiate” was used previously in this course to indicate constructing an object from a class. When you instantiate an object, it inherits all of the attributes and methods defined by the class. However, this isn’t always the case.

Sometimes the overhead of instantiating a complete object is unnecessary. Instead, you’ll need to rapidly refer to a single class member. You may make a class member static in such situation.

As with the hidden property, use the static keyword to make a class member static, as seen below.

$MaxClassCount = 7 class student [int]static

Unlike typical class members, PowerShell does not create properties and methods from static class members. When you define a class member as static, like Members Who Aren’t Visible, it doesn’t show up when you use Get-Member.

Members Who Remain StaticMembers Who Remain Static

For example, you could want to correlate university class titles with student courses and limit the number of university classes that a student can take. Create a Classes array member and a MaxClassCount member to do this.

Because the MaxClassCount member is seldom changed by the user, you decide to make it static.

Finally, an AddClass() function is created to add a class to the student’s schedule, but only if the number of classes is fewer than the MaxClassCount.

[string[]] student class $Classes = @() [int]static $MaxClassCount = 7 [void] $Classes = @() [int]static $Classes = @() [int]static $Classes AddClass ($Name) ([string]$Name) ([string]$Name) ([string]$Name $this.Classes += $Name if ($this.Classes.Count -lt [student]::MaxClassCount)

If you try to create a new student object with too many university courses assigned to it, PowerShell will only assign the maximum amount, which is seven.

$student1 = [student]::new() ‘PE’,’English’,’Math’,’History’,’Computer Science’,’French’,’Wood Working’,’Cooking’ | ForEach-Object { $student1.AddClass($_) } $student1.Classes

Count of Students in Each ClassCount of Students in Each Class

You may alter the values of static members at any moment. If you wanted the MaxClassCount member to be 5 instead of 7, for example, you’d alter the value using [student]:: MaxClassCount is set to 5. In this case, changing the value would not delete classes that are above the limit retrospectively.

Conclusion

The distinction between a scripting language and a programming language is obfuscated by PowerShell classes. Classes are a fantastic method to create object connections, provide ways to interact with, and format objects that would otherwise need the use of specific functions.

) ‘PE’,’English’,’Math’,’History’,’Computer Science’,’French’,’Wood $student1.Classes

Count of Students in Each ClassCount of Students in Each Class

You may alter the values of static members at any moment. If you wanted the MaxClassCount member to be 5 instead of 7, for example, you’d alter the value using [student]:: MaxClassCount is set to 5. In this case, changing the value would not delete classes that are above the limit retrospectively.

Conclusion

The distinction between a scripting language and a programming language is obfuscated by PowerShell classes. Classes are a fantastic method to create object connections, provide ways to interact with, and format objects that would otherwise need the use of specific functions.

The “powershell classes in modules” is a PowerShell class that allows users to create their own custom modules. The class will guide you through the process of creating your first module.

Frequently Asked Questions

How do I start learning PowerShell?

A: PowerShell is a command line shell and scripting language that works on Windows operating systems. It can be used to automate tasks in batches while also providing access to system information, files, registry keys, services, processes and the output from commands.

How do you create a class in PowerShell?

What are PowerShell classes?

A: PowerShell classes are structures that contain methods and properties. Class members can be inherited, or not, to create a hierarchy of class types.

Related Tags

  • powershell class constructor
  • powershell training
  • powershell nested classes
  • powershell get class
  • powershell class methods