Classes in PowerShell

 Classes in PowerShell


Classes are a new feature in PowerShell 5.0 that allow you to define custom objects with properties and methods. They provide a more structured and object-oriented approach to scripting in PowerShell. Here's an example:



class Person {

    [string]$Name

    [int]$Age


    Person([string]$Name, [int]$Age) {

        $this.Name = $Name

        $this.Age = $Age

    }


    [void] SayHello() {

        Write-Host "Hello, my name is $($this.Name) and I am $($this.Age) years old."

    }

}


$person = [Person]::new("John", 30)

$person.SayHello()

In this example, we define a class called Person with two properties (Name and Age) and a method (SayHello). We also define a constructor method that initializes the properties with values passed as arguments. We then create an instance of the class using the [Person]::new() method, passing in the name and age values. Finally, we call the SayHello() method on the instance to print a greeting to the console.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...