Of-course Powershell is OOP(Object oriented programming Tool). Which means any developer who know Object oriented Programming would know how to utilize it, that doesn’t mean who are not developers cannot learn Powershell. it’s bit annoying to understand the concepts of the OOP to take maximum use of it.
Classes aka Blueprints
Talking of concept of Classes Lets look at the inheritance in Powershell. How to write a script that will allow us to achieve the Inheritance from a class. Below diagram will show what does Inheritance look like.
There is a Class called Wallet which will basically have the certain base attributes such as Brand, Name of the Wallet, How many cards you can hold, how much money you can keep in it. These attributes are called as variables in the powershell class and the there are functions that a wallet can do, Such as: Spending function.
These are the 2 major characteristics of the Class.
Attributes
Functions
You can see from the below Powershell script that i have created a Class called Wallet. with some attribute and function that a wallet will have. In Powershell Attributes of a class is represented as Variables($brand,$name and etc) and Functions are represented as functions (SpendCash).
class Wallet{
[string] $Brand
[string] $Name
[string] $Card1
[float] $Card1Bal
[string] $Card2
[float] $Card2Bal
[string] $CashonHand
[string] $License
[void] SpendCash ([float]$spent){
$this.CashonHand -= $spent
}
}
$fazulwallet = New-Object Wallet
$fazulwallet.Name='Fazul Rahuman'
$fazulwallet.Brand = "LV"
$fazulwallet.Card1 = 'ABC Bank'
$fazulwallet.Card1Bal = 4000
$fazulwallet.Card2 = 'XYZ Bank'
$fazulwallet.Card2Bal = 1500
$fazulwallet.CashonHand = 500
$fazulwallet.License = "ABCED12341EWE2231"
$fazulwallet.SpendCash(100)
The class by itself doesn’t create the inheritance concept. Until you create a object from that class. $fazulwallet = New-Object Wallet once you create an Object. You now can use those attributes and function in your own object without defining anything, show below.
Now all you need to do it feed the data into the object like below. you can now as many wallets as you want and feed data into it.
We saw how the attributes work now lets look the functions, i created a function called SpendCash if you can see above image which shows i have 500 Cashonhand, Now i will use the function SpendCash to send a 100 from the cash i have in my wallet.
Now i have spent 100 form the cash i had in my wallet by simply running the function called SpendCash. Interesting isn’t it.
The purpose of the Class implementation in Powershell is to create runtime objects which could hold different values but use the same Class to instance an object. This Concept is also used in DSC resources.