Author Posts

April 9, 2015 at 3:43 pm

While going through Don Jones' "Ditch Excel" I have been testing some code and don't understand why I am seeing the results I am getting. I am trying to change the TypeName from ...PSCustomObject to Reports.ObjExam. When I run $objectCollection.pstypenames I see my expected result but when I pipe the variable to GM I still see the PSCusomObject.

In a separate script I have created a new object and used Insert() to assign a new TypeName, but in my code below I can't seem to make it work.
What did I do wrong?

$groups = 'Group101', 'Group102'
$users = 'User1', 'User2'

$properties = @{User=''; Group=''; Dummy = 'Default'}
$objectTemplate = New-Object -typename PSObject -Property $properties

$objectCollection=$groups | ForEach-Object{
    $groupCurrent = $_
        $users | ForEach-Object{
        $usersCurrent = $_

        $objectCurrent = $objectTemplate.PSObject.Copy()
        $objectCurrent.group = $groupCurrent
        $objectCurrent.user= $usersCurrent
        $objectCurrent
    }
}

$objectCollection | ft -autosize
$objectCollection.pstypenames.Insert(0,'Reports.ObjExam')
$objectCollection.pstypenames
$objectCollection | GM
 

April 9, 2015 at 9:51 pm

Hi Rich,

I believe I know why you are not seeing the new TypeName on your objects. You are inserting your type name into the $objectCollections array but not the actual objects you create inside the ForEach-Object block.

Working Example: PowerShell v2

$groups = 'Group101', 'Group102'
$users = 'User1', 'User2'
 
$objectCollection=$groups | ForEach-Object{
    $groupCurrent = $_
    $users | ForEach-Object{
        $usersCurrent = $_
 
        New-Object -TypeName PSObject -Property @{
            User = $usersCurrent
            Group = $groupCurrent
            Dummy = 'Default'
            PSTypeName = 'Reports.ObjExam'
        }
    }
}
 
$objectCollection[0].pstypenames[0]

Working Example: PowerShell v3 and later

$groups = 'Group101', 'Group102'
$users = 'User1', 'User2'
 
$objectCollection=$groups | ForEach-Object{
    $groupCurrent = $_
    $users | ForEach-Object{
        $usersCurrent = $_
 
        [PSCustomObject]@{
            User = $usersCurrent
            Group = $groupCurrent
            Dummy = 'Default'
            PSTypeName = 'Reports.ObjExam'
        }
    }
}
 
$objectCollection[0].pstypenames[0]

I hope above makes sense.

Best,
Daniel

April 10, 2015 at 3:45 pm

Thanks Daniel. That does make sense. I expected it to behave differently since I assigned the TypeName after the face but that seems like faulty reasoning on my side. Thanks for the reply, this helps!

Aloha
Rich