3

How can I view the memory address of the underlying object referenced by a variable in Powershell?

In C# I can do something like below but not sure how to do the equivalent in Powershell

int i;
int* pi = &i;

The reason for this is because of this below example giving different results depending on whether the script-block was dot-sourced or used the call-operator. The variable name is the same and when dot-sourced the updated value remains after the script-block has exited. This got me wondering if the call-operator implementation works on copies of the variables while the dot-source implementation is using the original variables.

PS C:\> $n = 1;&{$n = 2};$n
1 
PS C:\> $n = 1;.{$n = 2};$n
2

If I could do something like this it might help me understand whats happening...

PS C:\> $n = 1;&{$n.GetMemoryAddress()};
##########
PS C:\> $n = 1;.{$n.GetMemoryAddress()};
##########
5
  • 1
    What on earth are you going to do with the memory address of a shell variable? Commented Sep 25, 2014 at 11:08
  • I'm poking about trying to understand how things work... I want to see if a variable defined outside of but used inside of a script-block is pointing to the same object or a copy of it. I'm trying to understand the implementation implications of dot-sourcing a script-block vs using the call-operator on a script-block. : ) Commented Sep 25, 2014 at 11:20
  • So what you want is to get the address of an object not a variable? Commented Sep 25, 2014 at 11:21
  • Yeh, I guess so, the variable address would still be of interest but really I want the address of the underlying object. I will edit my question. Commented Sep 25, 2014 at 11:25
  • 1
    Get-Help about_Scopes would probably go a long way toward answering your questions. Commented Sep 25, 2014 at 12:49

2 Answers 2

4

If your real problem is finding out whether an object is being copied under the hood, maybe you don't need to look at its address. To find out if two objects are the exact same instance you can just use Object.ReferenceEquals:

[System.Object]::ReferenceEquals($a, $b)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Matti but this wont work in my context, added some further details of what I'm trying to achieve : )
0

You don't need to see the memory address. The call operator and dot sourced scripts do indeed run in different scopes. I am on mobile and can't easily offer you a link, but run get - help about_Scopes (or search for the same).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.