Saturday, October 26, 2013

Powershell: Array2Object function

I've been using Powershell a lot recently (I'll be blogging a lot more about it soon); sometimes, you get an array and it is convenient to transform it into an object (so we can apply select and similar operators to it); objects in powershell can be created with the New-Object cmdlet, and we pass it the kind of object; the basic powershell object is of type psobject, and we can use Add-Member to add a field to it (powershell objects, like in most scripting languages, can have fields added dynamically to them)

The following function will create an object, given an array ; the object have fields f1,f2 ... corresponding to the array elements 0,1,...

function array2Object($arr)
{
    $obj=New-Object psobject
    $fn=0;
    foreach($field in $arr) {
        ++$fn;
        Add-Member -InputObject $obj -MemberType NoteProperty -Name "f$fn" -value $field
    }
    return $obj
}