Powershell / .Net: Get a reference to an object returned by a method

Posted by Dan Menes on Stack Overflow See other posts from Stack Overflow or by Dan Menes
Published on 2010-05-22T15:56:22Z Indexed on 2010/05/22 16:00 UTC
Read the original article Hit count: 469

I am teaching myself PowerShell by writing a simple parser. I use the .Net framework class Collections.Stack. I want to modify the object at the top of the stack in place.

I know I can pop() the object off, modify it, and then push() it back on, but that strikes me as inelegant.

First, I tried this:

$stk = new-object Collections.Stack
$stk.push( (,'My first value') )
( $stk.peek() ) += ,'| My second value'

Which threw an error:

Assignment failed because [System.Collections.Stack] doesn't contain a settable property 'peek()'.
At C:\Development\StackOverflow\PowerShell-Stacks\test.ps1:3 char:12
+ ( $stk.peek <<<< () ) += ,'| My second value'
    + CategoryInfo          : InvalidOperation: (peek:String) [], RuntimeException
    + FullyQualifiedErrorId : ParameterizedPropertyAssignmentFailed

Next I tried this:

$ary = $stk.peek()
$ary += ,'| My second value'
write-host "Array is: $ary"
write-host "Stack top is: $($stk.peek())"

Which prevented the error but still didn't do the right thing:

Array is: My first value | My second value
Stack top is: My first value

Clearly, what is getting assigned to $ary is a copy of the object at the top of the stack, so when I the object in $ary, the object at the top of the stack remains unchanged.

Finally, I read up on teh [ref] type, and tried this:

$ary_ref = [ref]$stk.peek()
$ary_ref.value += ,'| My second value'
write-host "Referenced array is: $($ary_ref.value)"
write-host "Stack top is still: $($stk.peek())"

But still no dice:

Referenced array is: My first value | My second value
Stack top is still: My first value

I assume the peek() method returns a reference to the actual object, not the clone. If so, then the reference appears to be being replaced by a clone by PowerShell's expression processing logic.

Can somebody tell me if there is a way to do what I want to do? Or do I have to revert to pop() / modify / push()?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about powershell