Powershell / .Net: get a reference to the object returned by the method

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()?

+3
2

. , . , 2 , . .

+2

. "+ =", . , .Net. , -, :

$stk.push( @{"1"="My first value"} )
$stk.peek()["2"]="| My second value"
write-host "Stack top keys: $($stk.peek().keys)"
write-host "Stack top values: $($stk.peek().values)"

Stack top keys: 1 2
Stack top values: My first value | My second value

Collections.ArrayList

$item = new-object Collections.ArrayList
$stk.push( $item )
$stk.peek().Add( "My first value" )
$stk.peek().Add( "| My second value" )
$obj = $stk.peek()
$obj.Add( "| My third value" )
write-host "Stack top is: $($stk.peek())"

Stack top is: My first value | My second value | My third value
+1

Source: https://habr.com/ru/post/1746682/


All Articles