samaspin
samaspin

Reputation: 2402

Get Memory Address of Powershell Variable

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()};
##########

Upvotes: 2

Views: 3210

Answers (2)

briantist
briantist

Reputation: 47832

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).

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

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)

Upvotes: 3

Related Questions