I'm a PowerShell newbie, trying to understand scopes better. Is there a way to identify a scope from within the scope ? Some variable or function that would give me scope name or scope Guid or scope Id of some sort ?
How could I, for example, know if the local scope is the global scope ?
How could I, for example, know if the local scope is the global scope?
[bool] $isGlobalScope = -not $(try { Get-Variable -Scope 1 PSHOME } catch { })
$PSHOME is an automatic variable with option AllScope, so it is by definition present in each and very scope. It also has option Constant, which means that it cannot neither removed nor modified.
By asking Get-Variable to retrieve this variable from the parent scope, -Scope 1, the operation fails if you're in the global scope, because the global scope is the root of the entire scope hierarchy and therefore has no parent.
The upshot is:
If you're not in the global scope, the Get-Variable call succeeds and returns a nonempty string (PowerShell's home path).
-not operator coerces that string to a Boolean ([bool]), which evaluates to $false, given that nonempty strings are considered $true (irrespective of their content) and negation is applied.If you are in the global scope, the attempt to access -Scope 1 causes a statement-terminating error, which triggers the catch block of the try / catch / finally statement.
catch block takes no action, it behaves like $null in an expression context-not coerces $null to a Boolean. $null is $false in a Boolean context, so the negation with -not evaluates to $true, indicating that the code runs in the global scope.Note: Thread / background jobs and remote sessions have their own global scopes, and the test above cannot distinguish between them.
Note: The original form of this answer suggested (Get-PSCallStack).Count -eq 1 as a test; Get-PSCallStack outputs [System.Management.Automation.CallStackFrame] instances that describe the chain of invocations to the current scope in reverse order.
Therefore, however, this test doesn't detect running in the global scope via dot-sourcing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With