Table of Contents


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.
The lifetime of a PowerShell variable starts when it is declared. Local variables are deleted when the function is completed. In a host application/web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded into the same window.

By default functions don't return variables unless you call them. All created variables created in the function stays in the function unless you return it. Or if you use $global:variable but that's another topic. Example you create variable $a and $b, the function won't know which one to return therefore you must call it.

Local Variables

PowerShell protects access to variables, aliases, functions, and PowerShell drives (PSDrives) by limiting where they can be read and changed. By enforcing a few simple rules for scope, PowerShell helps to ensure that you do not inadvertently change an item that should not be changed.

The following are the basic rules of scope:

If you create an item in a scope, and the item shares its name with an item in a different scope, the original item might be hidden under the new item. But, it is not overridden or changed.

Global Variables

Example usage of a Global variable. The global variable below is called outside of the scope. When the Get-Service command runs, it looks back at the Global Variable and updates it.

get-service | Select @{Name="Item#";Expression={$global:i++;$global:i}},Name,Displayname,Status

This global variable can be then used in any other function/method as it retains the modified amount throughout the current runtime environment.

PS is pretty flexible, and anything left 'unclaimed', so to speak, will end up dropped to output. So, for example, if you have something that returns a value, or you just put a variable name on a line by itself, etc., PS will implicitly treat that as you having called Write-Output

In other words, these two commands have identical functionally:

Write-Output $hostname

same as invoking a variable which is faster then calling a commandlet