Does PowerShell support OOP? Does PowerShell support OOP? powershell powershell

Does PowerShell support OOP?


You can define new types in PowerShell v2.0 using the Add-Type cmdlet:

DETAILED DESCRIPTION

The Add-Type cmdlet lets you define a .NET class in your Windows PowerShell session. You can then instantiate objects (by using the New-Object cmdlet) and use the objects, just as you would use any .NET ob ject. If you add an Add-Type command to your Windows PowerShell profile, the class will be available in all Windows PowerShell sessions.

You can specify the type by specifying an existing assembly or source code files, or you can specify source code in line or saved in a variable. You can even specify only a method and Add-Type will define and generate the class. You can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in Windows PowerShell. If you specify source code, Add-Type compiles the specified source co de and generates an in-memory assembly that contains the new .NET types.

You can use the parameters of Add-Type to specify an alternate language and compiler (CSharp is the default), compiler options, assembly dependencies, the class namespace, and the names of the type and the resulting assembly.

help Add-Type for more information.

Also, see:


PowerShell is more of an OOP consumer language. It can utilize most of the .NET Framework but it doesn't natively support creating interfaces, classes and certainly not mixins. .NET, which PowerShell's type system is based upon, doesn't support mixins. PowerShell does support dynamic addition of properties and methods to an existing object via the Add-Member cmdlet.

Add-Type is useful but if you have to escape to C# or VB to define a class or a class that implements a particular interface, I wouldn't consider that first class support the creation of classes/interfaces.

If you looking for some free learning material, check out Effective Windows PowerShell.


Version 5 of Powershell seems to support some of mainstream OOP.

All credit goes to this guy: https://xainey.github.io/2016/powershell-classes-and-concepts/

Example of a class:

    class myColor    {        [String] $Color        [String] $Hex        myColor([String] $Color, [String] $Hex)        {            $this.Color = $Color            $this.Hex = $Hex        }        [String] ToString()        {            return $this.Color + ":" + $this.Hex        }    }

Example of an abstract class:

class Foo{    Foo ()    {        $type = $this.GetType()        if ($type -eq [Foo])        {            throw("Class $type must be inherited")        }    }    [string] SayHello()    {        throw("Must Override Method")    }}class Bar : Foo{    Bar ()    {    }    [string] SayHello()    {        return "Hello"    }}