Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Playing with learning PowerShell classes
- #Define a new class and give it a name (in this case, myClass)
- class myClass {
- #Give your new class properties
- [String]$Name
- [Int]$Age
- #Give your new class a method
- [Int]nextAge(){
- return $this.Age + 1
- }
- #Give your new class a constructor that does not require parameters
- myClass () {
- $this.Age = 0
- $this.Name = ''
- }
- #Give your new class a constructor that uses parameters to pre-load your values
- myClass ([string]$Name,[int]$Age) {
- $this.name = $name
- $this.age = $age
- }
- }
- # Instantiating the class using the blank constructor will return an effectively empty object,
- # except that the attributes will have been primed and typed to zero values
- $test = [myClass]::New()
- $test.Age # Will return 0
- $test.nextAge() # Will return 1
- $test.Age = 15 # Override the default age
- $test.Age # 15
- $test.nextAge() # 16
- # Instantiating the class using the second constructor will pre-load your values
- $person1 = [myClass]::new("Bob",27)
- $person1.Name # Bob
- $person1.nextAge() # 28
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement