Advertisement
sunraycafe

Powershell Classes

Dec 22nd, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Playing with learning PowerShell classes
  2.  
  3. #Define a new class and give it a name (in this case, myClass)
  4. class myClass {
  5.  
  6.     #Give your new class properties
  7.     [String]$Name
  8.     [Int]$Age
  9.  
  10.     #Give your new class a method
  11.     [Int]nextAge(){
  12.         return $this.Age + 1
  13.     }
  14.  
  15.     #Give your new class a constructor that does not require parameters
  16.     myClass () {
  17.         $this.Age = 0
  18.         $this.Name = ''
  19.     }
  20.    
  21.     #Give your new class a constructor that uses parameters to pre-load your values
  22.     myClass ([string]$Name,[int]$Age) {
  23.         $this.name = $name
  24.         $this.age = $age
  25.     }
  26. }
  27.  
  28. # Instantiating the class using the blank constructor will return an effectively empty object,
  29. # except that the attributes will have been primed and typed to zero values
  30. $test = [myClass]::New()
  31.  
  32. $test.Age        # Will return 0
  33. $test.nextAge()  # Will return 1
  34.  
  35. $test.Age = 15   # Override the default age
  36.  
  37. $test.Age        # 15
  38. $test.nextAge()  # 16
  39.  
  40.  
  41. # Instantiating the class using the second constructor will pre-load your values
  42. $person1 = [myClass]::new("Bob",27)
  43.  
  44. $person1.Name       # Bob
  45. $person1.nextAge()  # 28
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement