How to create real objects with behavior (methods) in PowerShell?

后端 未结 3 502
名媛妹妹
名媛妹妹 2021-02-07 23:18

Probably this question has been answered before.... but I have not found a specific answer to my needs.

BTW I\'m using PowerShell 3

Well, I\'m new in PowerShell

相关标签:
3条回答
  • 2021-02-07 23:48

    If you want full OOP (including inheritance, although not interfaces), then PSClass is an MS-PL licensed implementation.

    0 讨论(0)
  • 2021-02-07 23:55

    Two options to create object with methods:

    1. Add-Member
    2. New-Module -AsCustomObject

    Code samples:

    $person | Add-Member -MemberType ScriptMethod -Value {
        'I do stuff!'
    }
    
    $person = New-Module -AsCustomObject -ScriptBlock {
        $Property = 'value'
        [string]$Other = 'Can be strongly typed'
    
        function MyMethod {
            'I do stuff!'
        }
    
    }
    

    EDIT: speaking of private/ public... In latter example property won't show up "by default". You can decide what is public using Export-ModuleMember and specify -Variable (properties) and/or -Function (methods) that will be public. Without explicit Export-ModuleMember it will behave same as in "normal" module - export only functions (methods).

    0 讨论(0)
  • 2021-02-08 00:10

    PowerShell v5 introduces full class support, making it easy to build your own classes with properties and implement methods.

    Check out Trevor's great blog post about the topic here. Trevor Sullivan, Implementing a .net Class

    Standalone Example

    Here is a PowerShell class of a made up type called a Fox, which has a .Deploy() method, should show how this is done

    class Fox {
        # describes the sixe of the fox
        [String] $Size;
        # Property: the foxes color
        [String] $Color;
    
        # Constructor: Creates a new Fox object, with the specified
        #              size and name / owner.
        Fox([string] $NewSize, [String] $NewName) {
            # describes the sixe of the fox
            $this.Size = $NewSize;
            # Property: the foxes color
            $this.Color = $NewName;
        }
    
        # Method: Change the size of the fox     
        [void] Morph([UInt32] $Amount) {
            try {
                $this.Size = $this.Size - $Amount;
            }
            catch {
                Write-Warning -Message 'You tried to set an invalid size!';
            }
        }
    
        # Method: BreakGlass resets the beer size to 0.
        [void] Deploy() {
            Write-Warning -Message "The $($this.Color) fox, which is $($this.Size) in stature, goes off into the distance"        
        }
    }
    

    And in practice:

    0 讨论(0)
提交回复
热议问题