Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does powershell 5 class have access modifiers?

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)
  {
  }
}
like image 784
Nayana Adassuriya Avatar asked Sep 10 '17 02:09

Nayana Adassuriya


1 Answers

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

like image 136
Sage Pourpre Avatar answered Oct 06 '22 00:10

Sage Pourpre