I teach myself PowerShell by writing a simple parser. I am using the .Net framework class Collections.Stack. I want to change the object at the top of the stack in place.
I know that I can turn off an object pop(), change it, and then push()turn it back on, but it strikes me as inelegant.
First, I tried this:
$stk = new-object Collections.Stack
$stk.push( (,'My first value') )
( $stk.peek() ) += ,'| My second value'
What caused the 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())"
This prevented the error, but still did not work:
Array is: My first value | My second value
Stack top is: My first value
Obviously, the purpose of $ ary is a copy of the object at the top of the stack, so when I am an object in $ ary, the object at the top of the stack remains unchanged.
Finally, I read the [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 there are still no dice:
Referenced array is: My first value | My second value
Stack top is still: My first value
, peek() , . , , -, PowerShell.
- , , ? pop()/modify/push()?