How to create simple DTO “object” in PowerShell

Why this sample :

I needed simple and short solution for creating custom DTO objects with simple logic for later reuse elsewhere. Function essentialy takes “constructor” argument and returns object with properties that have getters with small piece of logic and are using constructor parameter. No inheritance, no access modificators or any advanced OOP stuff. Just above mentioned functionality as “helper”. There are many other way of creating object in PowerShell (that also vary from PowerShell version to version – I used v4 here), but I needed something I can have in a function to call several times in a loop and create array of these objects.

Code :

function getMeMyObject {
	[CmdletBinding()]
	Param([Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][string]$propertyName)

    Process {
        $retObj = @{}

        $retObj | Add-Member -Name Prop1 -MemberType ScriptProperty -Value {
            'Prop1-' + $propertyName
        }.GetNewClosure()

        $retObj | Add-Member -Name Prop2 -MemberType ScriptProperty -Value {
            'Prop2-' + $propertyName
        }.GetNewClosure()

        return $retObj
    }
}

Usage :

Just call the function and assign the output to the variable of your choice.

$yourVar = getMeMyObject -propertyName 'qqqq'

I strongly typed variable -propertyName so it has to be string, but it’s just for purpose of this demo, feel free to modify this snippet as you like/need.

There is only one small thing worth notice, the “secret” why at runtime we can access the input variable -propertyName is quite simple. I am calling

.GetNewClosure()

after each getter code, which is capturing all the variables. Without this the property

$propertyName

would be empty but code will not fail which is quite tricky I would say. You can try for your self 🙂

More on this method here : http://blogs.msdn.com/b/powershell/archive/2009/03/27/get-closure-with-getnewclosure.aspx and here http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/10/hey-scripting-guy-weekend-scripter-getting-closure-with-the-getnewclosure-method.aspx.

Other great article can be found here : http://www.padisetty.com/2014/05/all-about-powershell-scriptblock.html

Two possible versions of calling :

You can use two methods of calling the code. Either use dedicated .ps1 file with function in it, or inline copy a script block that creates variable you can call, choice is yours.

Code repo :

Feel free to play here : https://github.com/rostacik/PSCreateObjectFromFunctionSample

Leave a Reply

Your email address will not be published. Required fields are marked *