Monthly Archives: April 2015

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 {

    Process {
        $retObj = @{}

        $retObj | Add-Member -Name Prop1 -MemberType ScriptProperty -Value {
            'Prop1-' + $propertyName

        $retObj | Add-Member -Name Prop2 -MemberType ScriptProperty -Value {
            'Prop2-' + $propertyName

        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


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


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 : and here

Other great article can be found here :

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 :

Simple PowerShell snippet to search file or array for content

Since I play these days a lot with PowerShell I need from time to time some simple functionality. Sometimes dead simple. Like today , snippet to search file content or array of data if you will and return true/false if text is present in it.

function File-Contains-Row {
	Param([array]$fileContent, [string]$searchedString)

	Process {
		#is there any string we search for in any of the rows?
		[array]$resArray = $fileContent | where { $_ | Select-String –caseSensitive -Pattern $searchedString }

		if ($resArray.Count -eq 0) {
			return $false
		} else {
			return $true

As a project, you can find it here :

.ps1 file is here :