Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 but I have a lot of experience as a C# developer, so working with objects is very important to me.

So I'm wondering if there's a clean way to apply OOP concepts (well not all of them, though that would be awesome) in a PowerShell script, for example there are specific things that I would like to do.

Note: I'm aware that I can write C# code in PowerShell to create DTO's and also that I can create PowerShell binary modules in C#, I have done that in the past, but what I'm looking for now is the ability to write all my code in PowerShell but in an Object Oriented way.

Things I would like to do:

  • Create an object in PowerShell, and expose a function written in PowerShell as well, something like this:

    function New-Person
    (
        [Parameter()][string]$firstName
    )
    {
        function Walk()
        {
            Write-Host "Walking...";
        }
    
        $person = New-Object psobject;
    
        $person | Add-Member -MemberType NoteProperty -Name FirstName -Value $firstName;
    
        #This line does not work
        #$person | Add-Member -MemberType CodeMethod -Name Walk -Value Walk;
    
        return $person;
    }
    
    $MyPerson = New-Person -firstName "JP";
    
    $MyPerson;
    
    #This line does not work
    $MyPerson.Walk();
    
  • Encapsulate behavior, which means create functions inside my object and then mark them as private

  • [Nice to have]. Create base classes so I can inherit and specialize my behavior overriding methods

  • [Nice to have]. Create interfaces so I can start thinking in unit testing in isolation my PowerShell methods (I know there are tools like Pester to do this I'm just focusing on OOP features)

What I have done so far is creating objects with properties only (DTO's) but I'd like to add behavior to my objects

I'd appreciate if you guys point me in the right direction

like image 685
Jupaol Avatar asked Feb 12 '13 15:02

Jupaol


People also ask

Can you create objects in PowerShell?

One way to create your own objects is by using hashtables. Hashtables are sets of key/value pairs precisely what you need for creating properties for an object. Let's start by creating a custom PowerShell object with some key/values using a hashtable. In the below example, you are creating a hashtable.

What PowerShell Commandlet returns the properties and methods of objects?

The Get-Member cmdlet gets the members, the properties and methods, of objects. To specify the object, use the InputObject parameter or pipe an object to Get-Member .

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'


1 Answers

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: enter image description here

like image 111
FoxDeploy Avatar answered Oct 05 '22 06:10

FoxDeploy