user1575786
user1575786

Reputation: 69

How to create an object of a custom class in Window PowerShell console?

I have created a simple class using Windows PowerShell ISE. The class definition is as follows.

class Person {
 [string] $FirstName
 [string] $LastName
    
    Person() {        
    }
    
    [string] Greeting() {
        return "Greetings, {0} {1}!" -f $this.FirstName, $this.LastName
    }
}

Now from within PowerShell console when I attempt to create an object from this class like this:

$x = [Person]::new()

It says

Unable to find type [Person].

Upvotes: 1

Views: 613

Answers (1)

Alex Korobchevsky
Alex Korobchevsky

Reputation: 165

Your class definition is perfectly valid. The easiest way of starting to use your class is adding code in the same file below:

class Person {
 [string] $FirstName
 [string] $LastName
    
    Person() {        
    }
    
    [string] Greeting() {
        return "Greetings, {0} {1}!" -f $this.FirstName, $this.LastName
    }
}

# Using constructor
$x = [Person]::new()

# Setting up properties
$x.FirstName = "Alex"
$x.LastName = "K"

# Running a method
$x.Greeting()

Greetings, Alex K!

Upvotes: 2

Related Questions