Does PowerShell support OOP?

2020-07-06 06:45发布

问题:

What is about such concepts as Class, Interface, Mixin in PowerShell? Does it support OOP? If so, where can I read about this?

回答1:

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:

  • How do I create a custom type in PowerShell for my scripts to use?

  • http://thepowershellguy.com/blogs/posh/archive/2008/06/02/powershell-v2-ctp2-making-custom-enums-using-add-type.aspx



回答2:

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.



回答3:

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"
    }
}


回答4:

The PowerShell pipeline deals with objects, not just a text stream a a Unix pipeline does. All variables are instances of objects as well. These are all .NET objects, BTW.

Here's part of the output of an "ls" command piped to the get-member cmdlet:

    PS C:\Documents and Settings\Administrator.DEV-3DPST1-SWK> ls | get-member


   TypeName: System.IO.DirectoryInfo

Name                      MemberType     Definition
----                      ----------     ----------
Create                    Method         System.Void Create(DirectorySecurity directorySecurity), System.Void Create()
CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
CreateSubdirectory        Method         System.IO.DirectoryInfo CreateSubdirectory(String path), System.IO.Director...
Delete                    Method         System.Void Delete(), System.Void Delete(Boolean recursive)
Equals                    Method         System.Boolean Equals(Object obj)
GetAccessControl          Method         System.Security.AccessControl.DirectorySecurity GetAccessControl(), System....
GetDirectories            Method         System.IO.DirectoryInfo[] GetDirectories(String searchPattern), System.IO.D...
GetFiles                  Method         System.IO.FileInfo[] GetFiles(String searchPattern), System.IO.FileInfo[] G...
GetFileSystemInfos        Method         System.IO.FileSystemInfo[] GetFileSystemInfos(String searchPattern), System...
GetHashCode               Method         System.Int32 GetHashCode()
GetLifetimeService        Method         System.Object GetLifetimeService()
GetObjectData             Method         System.Void GetObjectData(SerializationInfo info, StreamingContext context)
GetType                   Method         System.Type GetType()
get_Attributes            Method         System.IO.FileAttributes get_Attributes()
get_CreationTime          Method         System.DateTime get_CreationTime()

get-member displays the members of the object you pipe to it. You can see that these are the actual members of the System.IO.DirectoryInfo class.