PowerShell: how to create a link to object objects

Some facts:

When you assign an object to a variable named $a , and then one of its properties changes, the variable $a changes.

But when I assign the value of the property of the object $object.property (instead of the object itself) to a variable named $b , and then $object.property changes, $b not updated. This means that the current value is stored in $object.property , but $b remains as it is.

Example:

I am assigning a Window object to a variable named $bochsWindow . Then some properties change because I am moving the window. But when I print $bochsWindow , you can see that it is updated - this means that all new property values โ€‹โ€‹of the object are also stored in $bochsWindow .

But if you try to save the $bochsWindow property in a variable called $posX , and then the property changes, $posX does not change.

 PS .> $bochsWindow = (GetProcess bochs | Get-Window) PS .> $bochsWindow ProcessId : 1536 ProcessName : bochs Position : {X=54,Y=32,Width=650,Height=576} IsMinimized : False IsMaximized : False WindowHandle : 3933134 Caption : Bochs for Windows - Display [[Moving Boch Window By Hand]] PS .> $bochsWindow ProcessId : 1536 ProcessName : bochs Position : {X=0,Y=0,Width=650,Height=576} IsMinimized : False IsMaximized : False WindowHandle : 3933134 Caption : Bochs for Windows - Display PS .> (Get-Window -ProcessName bochs) ProcessId : 1536 ProcessName : bochs Position : {X=0,Y=0,Width=650,Height=576} IsMinimized : False IsMaximized : False WindowHandle : 3933134 Caption : Bochs for Windows - Display PS .> $posX = $bochsWindow.Position.X PS .> $posX 302 [[Moving Boch Window By Hand]] PS .> $posX 302 PS .> $bochsWindow.Position.X 472 PS .> 

But what should I do if I want $posX stay updated and always keep the new value ( 472 ) instead of 302

My question is:

I want to save a reference to an object property in a variable. This means that I want the variable to be updated every time the property of the object changes. How can i do this? Thanks.

+4
source share
2 answers

A PSBreakpoint trivial way to use PSBreakpoint , but this is the only thing I know:

 $global:bochsWindow = (GetProcess bochs | Get-Window) $act= @' $global:b = $bochsWindow.Position.X '@ $global:sb = [scriptblock]::Create($act) $global:b = Set-PSBreakpoint -Variable b -Mode Read -Action $global:sb 

Thus, $b always updated on invocation.

+6
source

Why don't you just create a function?

 function posX(){ $bochsWindow.Position.X } 

And then use it as posX . An alternative would be a script block.

Other than that, I see no direct way to do this.

+3
source

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


All Articles