As part of my Powershell script I need to, essentially, implement breadth-first search. So, I need queue and figured System.Collections.Queue is as good as any other queue. However, when I get an object out of the queue, Powershell loses track of any properties I've added to the object.
What's going on here? How do I access my property?
This sample demonstrates the problem:
$object = new-object object
add-member -membertype noteproperty -name AnInteger -value 2 -inputobject $object
$queue = new-object system.collections.queue
$queue.enqueue($object)
$dequeued = $queue.dequeue()
# 1. True - both variables refer to the same object.
$object -eq $dequeued
# 2. True - using the original variable, can access the property.
$object.AnInteger -ne $null
# 3. False. Err, What?
$dequeued.AnInteger -ne $null
I found my mistake: add-member modifies an instance of PSObject not Object. It looks like it created one for me to wrap $object before adding the property. So, I needed to either create a PSObject or cast the result of dequeue to PSObject.
I still don't understand everything that's going on here. Did add-member modify $object to refer to the PSObject it created? If not, how did the Powershell run-time know that $object was in fact a PSObject? $object.gettype().name is Object not PSCustomObject.
When you use PsObject, it works. However, I have no idea why it doesn't work on the .NET Object
$object = new-object PsObject -property @{AnInteger=2}
$queue = new-object system.collections.queue
$queue.enqueue($object)
$dequeued = $queue.dequeue()
$object.Aninteger -eq $dequeued.AnInteger # returns True
The same holds obviously for other .NET collections as well:
$mynum = 10 | add-member noteproperty MySecret 12345 -pass
$mynum.mysecret
$list = New-Object collections.arraylist
$list.Add($mynum)
$list[0].mysecret
$list[0] | fl * -force # shows nothing
$mynum | fl * -force # shows mysecret
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With