Is there a way to control the access of members in Powershell classes? As the same way we do in c++ or C#. How can we write below C# class in Powershell
class Car
{
  private string engine;
  public string wheel_type;
  public void drive()
  {
  }
  private int change_engine(string new_engine)
  {
  }
}
                Starting in PowerShell 5.0, PowerShell adds class support.
Please note that PowerShell does not offer a private keyword though. You can, however, use the hidden keyword, which will hide the property / method from the intellisense by default (although it can be forced to appear) and the Get-Member cmdlet won't return the hidden members unless the -Force switch is used.
Here is a sample car class which demonstrate a bit of everything.
enum Engine {
    None
    V4
    V8
}
Class Car
{    
    static [int]$numberOfWheels = 4
    [int]$numberOfDoors
    [datetime]$year
    [String]$model
    [Engine]$Engine 
    car() {
    #Constructor ... optional
    }
    car([Engine]$Engine,$numberofDoors = 4 ) {
    #Constructor overload with default value... optional
    $this.Engine = $Engine
    $this.numberOfDoors = $numberofDoors
    }
    drive()
    {
    }
    hidden [int] change_engine([string] $new_engine) {
        return 0
    }
}
# Call to static property
[Car]::numberOfWheels
#Create Car object
$MyCar = New-Object Car([Engine]::V4,4)
#Call drive
$MyCar.drive()
References
4syops - PowerShell classes (series of 4)
Microsoft PowerShell docs: About Classes
Sapien.com - Hidden keyword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With