1

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].

4
  • 1
    Did you run the code to load the class in memory? Or did you dot source the file? Or did you using module? Commented Feb 7, 2022 at 17:35
  • 2
    This is as expected. Defining a new type in one process doesn't automatically define it in another. Commented Feb 7, 2022 at 17:39
  • 1
    Save the class as file "Person.ps1". Assuming you are in the same directory in the console, type: . .\Person.ps1 to make the class available in the console. Note the space between the two dots! This is called dot-sourcing. Not the most scalable approach, but easy to use for simple stuff. Commented Feb 7, 2022 at 19:44
  • Ok. I dot-sourced my script and I'm able to successfully create the object like the following . F:\Per\PowerShell\PowerShell_Classes.ps1 $myobj = [Person]::new() Bundle of thanks Commented Feb 8, 2022 at 15:54

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.