Variable declared inside nested statement can be used outside of that statement?

Can you isolate a variable inside curly brackets so that it’s not usable outside of those brackets? I find it weird that you can still use a variable even if it’s created inside a nested statement. Is this how Powershell works?

    if($myOtherNumber -eq 2){[byte[]]$switchScope=12,34,56}
Get-Variable -Scope local # $switchScope IS LISTED
$switchScope # VALUES 12,34,56 ARE DISPLAYED
             # WHY IS $switchScope NOT $null HERE?

If it is not called out as possible in the about_Scopes help file, then it is not really a thing. As per the below there is no such thing as a statement scope.

PowerShell Scopes

Scopes in PowerShell have both names and numbers. The named scopes specify an absolute scope. The numbers are relative and reflect the relationship between scopes.

• Global: The scope that is in effect when PowerShell starts. Variables and functions that are present when PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your PowerShell profiles.

• Local: The current scope. The local scope can be the global scope or any other scope.

• Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.

• Private: Items in private scope cannot be seen outside of the current scope. You can use private scope to create a private version of an item with the same name in another scope.

• Numbered Scopes: You can refer to scopes by name or by a number that describes the relative position of one scope to another. Scope 0 represents the current, or local, scope. Scope 1 indicates the immediate parent scope. Scope 2 indicates the parent of the parent scope, and so on. Numbered scopes are useful if you have created many recursive scopes.

More detail on Private from the PS creator himself - ‘Private Scope’:

Yep, this is how PowerShell is. It’s much looser in how it determines scope. If you want to bury a variable in a scope, define that code sequence as a function; variables defined inside a function are not accessible outside it. :slight_smile: