How to create global variable but without to use "global:" - powershell

How to create subj, but absolutely the same as $null, without any "global:" prefix AND this variable should be available anywhere in such notation, in functions body, for example? Powershell is 6.0.3 (Linux)

As for my knowledge this is not possible since you need to define the scope of a variable to use it globally within functions.
It might work to put the variable in a separate .ps1 file and dot-source it in the body and and in every function you want to access its data. But changing the variables value won't be global, therefore it would be "read only".

How about New-Variable cmdlet?
new-variable -scope global -name a -value "One"
also, check about_scopes help file
get-help about_scopes

Related

Global variable not being picked up by function [duplicate]

If I declare and initialize a PowerShell variable with $global:MyVariable = "123" do I then need to use $global: anywhere I use the variable or can I just use $MyVariable?
In principle you can use just $MyVariable to reference the value of a global variable by that name, but you may see a different variable's value, situationally.
Specifically, if any intervening ancestral (parent) scope or even the calling scope itself has also created a $MyVariable variable (which typically happens implicitly by simple assigmnent; e.g., $MyVariable = ...), you will see that variable's value instead.
You're only guaranteed to see the global value if you do use the global scope specifier, namely: $global:MyVariable (or Get-Variable -ValueOnly -Scope Global MyVariable)[1]
By default, variables are visible, but not directly modifiable in all descendant (child) scopes.
Therefore you must use $global:MyVariable / Set-Variable -Scope Global in order to modify (set) a global variable; without $global: you'll implicitly create a local variable by the same name.
For more on PowerShell's scoping rules, see the last section of this answer.
[1] In real-world scenarios, even code in PowerShell modules sees global variables with scope specifier $global:, and the implicit visibility of global variables always applies.
For in-memory modules, there is a way to make $global / -Scope global refer to a different scope, namely the module's own top-level scope, but the technique is obscure, not documented, and its real-world utility is unknown.
Read on, if you want to know more.
Optional reading: Creating an in-memory module that sees its own top-level scope as the global scope:
PetSerAl has discovered a little-known way to create an in-memory module in a manner that makes it see $global: / -Scope global as its own top-level scope rather than the true global scope - curiously, not using an explicit scope reference makes the code still see (non-shadowed) global variables:
$global:MyVariable = 42 # Create a true global variable.
# Create an in-memory module for which its *own top-level scope*
# becomes the "global" scope, by virtue of passing $false to the
# [psmoduleinfo] constructor:
& ([psmoduleinfo]::new($false)) {
#"
"$global:MyVariable",
"$(Get-Variable -ValueOnly -Scope global MyVariable)",
"$MyVariable"
"#
}
yields:
Get-Variable : Cannot find a variable with the name 'MyVariable'.
# ...
"", # $global:MyVariable didn't find the variable
", # Neither did Get-Variable -Scope Global (see error above)
"42" # OK - implicit visibility of true global variables
Note that neither New-Module nor Import-Module (for persisted modules) offer this functionality.
The obscure & <module-info> { ... } technique used above for invoking a script block in a module's scope is explained in this excellent blog post by Patrick Meinecke.
Run this and see that it is best to always specify, if you don't you will not alwys get what you might expect
function func {
"0. $myvar"
$myvar='funclocal'
"1. $myvar"
"2. $Global:myvar"
}
$Global:myvar='global'
func
"3. $Global:myvar"
you do not need to use $global: when calling

Dot Sourced Variables VS Global Variables

I have two ways of referencing script variables from a separate script file. Here are two basic examples:
1. Dot Source
Variables.ps1
$Source = "source"
$Destination = "dest"
Execute.ps1
. .\Variables.ps1
Copy-Item -Path $Source -Destination $Destination -Force
2. Global Variable
Variables.ps1
$Global:Source = "source"
$Global:Destination = "dest"
Execute.ps1
.\Variables.ps1
Copy-Item -Path $Source -Destination $Destination -Force
I have done research but have yet to find a definitive reason as to use one over the other. Are there limitations or cautions I should exercise when using these methods? Any input is greatly appreciated. Thank you for your time.
EDIT:
#mklement0 gave a great answer as to why to use dot-sourcing over global variables. I would love to still keep this discussion open. If there is another point of view, or an explanation as to when using global variables is more beneficial, I would enjoy hearing it and up-voting accordingly. Thank you.
I suggest you use dot-sourcing, without explicit global variables (method 1):
That way, it requires a deliberate effort to add variables to the current scope. Note that dot-sourcing adds the variables to the current scope, which may or may not be the current session's global scope (child scopes are created by calling scripts (without dot-sourcing) and script blocks with &, for instance).
By contrast, using global variables (method 2) creates session-global variables irrespective of invocation method, so that even accidental, non-dot-sourced invocations of the script end up altering the global state.

Are Powershell Profile scripts dot-sourced?

The Microsoft.PowerShell_profile.ps1 script I am using creates a lot of variables when it runs. I have set all the variables' scope to "Script", but the variables used in the script never go out-of-scope.
I would like the variables to go out-of-scope once the script is done running and control is handed over to me.
If I compare the number of global, local, and script variables I have, I come up with the same number.
Example:
# Profile script does what it does.
Get-Variable -Scope Global | Measure-Object
Get-Variable -Scope Local | Measure-Object
Get-Variable -Scope Script | Measure-Object
Output:
60
60
60
Currently, I am capturing a snapshot of the variables at the beginning of my profile script, then removing any new variables at the end.
Example:
$snapshotBefore = Get-Variable
$profileVar1 = 'some value'
$profileVar2 = 'some other value'
$snapshotAfter = Get-Variable
# Compare before and after, and create list of new variables.
Remove-Variable $variablesToRemove
Yes, PowerShell profiles are dot-sourced by design, because that's what allows the definitions contained in them (aliases, functions, ...) to be globally available by default - which is, after all, the main purpose of profile files.
Unfortunately, there is no scope modifier that allows you to create a temporary scope for variables you only want to exist while the profile is loading - even scope local is effectively global in a profile script; similarly, using scope private is also not an option, because the profile's script scope - due to being dot-sourced - is the global scope.
Generally speaking, you can use & (the call operator) with a script block to create variables inside that block that are scoped to that block, but that is usually at odds with creating globally available definitions in a profile, at least by default.
Similarly, calling another script without dot-sourcing it, as in your own answer, will not make its definitions globally available by default.
You can, however, create global elements from non-dot-sourced script blocks / script by specifying the global scope explicitly; e.g.: & { $global:foo = 'Going global' }, or & { function global:bar { 'global func' } }.
That said, the rationale behind dot-sourcing profiles is likely that it's easier to make all definitions global by default, making the definition of typical elements of a profile - aliases, functions, drive mappings, loading of modules - simpler (no need to specify an explicit scope).
By contrast, global variables are less typical, and to define the typical elements listed above you don't usually need script-level (and thus global) variables in your profile.
If you still need to create (conceptually) temporary variables in your profile (which is not a requirement for creating globally available aliases, functions, ...):
A simple workaround is to use an exotic variable name prefix such as __ inside the profile script to reduce the risk of their getting referenced by accident (e.g, $__profileVar1 = ...).
In other words: the variables still exist globally, but their exotic names will typically not cause problems.
However, your approach, even though it requires a little extra work, sounds like a robust workaround, here's what it looks like in full (using PSv3+ syntax):
# Save a snapshot of current variables.
# * If there are variables that you DO want to exist globally,
# define them ABOVE this command.
# * Also, load MODULE and dot-source OTHER SCRIPTS ABOVE this command,
# because they may create variables that *should* be available globally.
$varsBefore = (Get-Variable).Name
# ... define and use temporary variables
# Remove all variables that were created since the
# snapshot was taken, including $varsBefore.
Remove-Variable (Compare-Object $varsBefore (Get-Variable).Name).InputObject
Note that I'm relying on Compare-Object's default behavior of only reporting differences between objects and, assuming you haven't tried to remove any variables, only the variables added are reported.
Note that while it can be inferred from the actual behavior of profile files that they are indeed dot-sourced - given that dot-sourcing is the only way to add elements to the current scope (the global scope, in the case of profiles) -
this fact is not explicitly documented as such.
Here are snippets from various help topics (as of PSv5) that provide clues (emphasis mine):
From Get-Help about_Profiles:
A Windows PowerShell profile is a script that runs when Windows PowerShell
starts. You can use the profile as a logon script to customize the
environment. You can add commands, aliases, functions, variables, snap-ins,
modules, and Windows PowerShell drives. You can also add other
session-specific elements to your profile so they are available in every
session without having to import or re-create them.
From Get-Help about_Variables:
By default, variables are available only in the scope in which
they are created.
For example, a variable that you create in a function is
available only within the function. A variable that you
create in a script is available only within the script (unless
you dot-source the script, which adds it to the current scope).
From Get-Help about_Operators:
. Dot sourcing operator
Runs a script in the current scope so that any functions,
aliases, and variables that the script creates are added to the current
scope.
From Get-Help about_Scopes
But, you can add a script or function to the current scope by using dot
source notation. Then, when a script runs in the current scope, any
functions, aliases, and variables that the script creates are available
in the current scope.
To add a function to the current scope, type a dot (.) and a space before
the path and name of the function in the function call.
So it does sounds like Powershell dot-sources the profile. I couldn't find a resource that specifically says that, or other forums that have asked this question.
I have found an answer, and wanted to post it here.
I have changed my profile to only call a script file. The script now has its own scope, and as long as the variables aren't made global, they will go out-of-scope once the profile finishes loading.
So now my profile has one-line:
& (Split-Path $Path $profile -Parent | Join-Path "Microsoft.PowerShell_profile_v2.ps1")
Microsoft.PowerShell_profile_v2.ps1 can now contain proper scope:
$Global:myGlobalVar = "A variable that will be available during the current session"
$Script:myVar = "A variable that will disappear after script finishes."
$myVar2 = "Another variable that will disappear after script finishes."
What this allows, is for the profile script to import modules that contain global variables. These variables will continue to exist during the current session.
I would still be curious why Microsoft decided to call the profile in this way. If anyone knows, and would like to share. I would love to see the answer here.

Any example to show "Numbered Scopes" concept? [duplicate]

A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.
But there is another thing that surprised me is that variables behave as a copy-on-write within an inner scope.
$array=#("g")
function foo()
{
$array += "h"
Write-Host $array
}
& {
$array +="s"
Write-Host $array
}
foo
Write-Host $array
The output is:
g s
g h
g
Which makes dynamic scoping a little bit less painful. But how do I avoid the copy-on-write?
The PowerShell scopes article (about_Scopes) is nice, but too verbose, so this is quotation from my article:
In general, PowerShell scopes are like .NET scopes. They are:
Global is public
Script is internal
Private is private
Local is current stack level
Numbered scopes are from 0..N where each step is up to stack level (and 0 is Local)
Here is simple example, which describes usage and effects of scopes:
$test = 'Global Scope'
Function Foo {
$test = 'Function Scope'
Write-Host $Global:test # Global Scope
Write-Host $Local:test # Function Scope
Write-Host $test # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 0) # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 1) # Global Scope
}
Foo
As you can see, you can use $Global:test like syntax only with named scopes, $0:test will be always $null.
You can use scope modifiers or the *-Variable cmdlets.
The scope modifiers are:
global used to access/modify at the outermost scope (eg. the interactive shell)
script used on access/modify at the scope of the running script (.ps1 file). If not running a script then operates as global.
(For the -Scope parameter of the *-Variable cmdlets see the help.)
Eg. in your second example, to directly modify the global $array:
& {
$global:array +="s"
Write-Host $array
}
For more details see the help topic about_scopes.
Not just varibles. When this says "item" it means variables, functions, aliases, and psdrives. All of those have scope.
LONG DESCRIPTION
Windows PowerShell protects access to variables, aliases, functions, and
Windows PowerShell drives (PSDrives) by limiting where they can be read and
changed. By enforcing a few simple rules for scope, Windows 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:
- An item you include in a scope is visible in the scope in which it
was created and in any child scope, unless you explicitly make it
private. You can place variables, aliases, functions, or Windows
PowerShell drives in one or more scopes.
- An item that you created within a scope can be changed only in the
scope in which it was created, unless you explicitly specify a
different scope.
The copy on write issue you're seeing is because of the way Powershell handles arrays. Adding to that array actually destroys the original array and creates a new one. Since it was created in that scope, it is destroyed when the function or script block exits and the scope is disposed of.
You can explicitly scope varibles when you update them, or you can use [ref] objects to do your updates, or write your script so that you're updating a property of an object or a hash table key of an object or hash table in a parent scope. This does not create a new object in the local scope, it modifies the object in the parent scope.
While other posts give lots of useful information they seem only to save you from RTFM.
The answer not mentioned is the one I find most useful!
([ref]$var).value = 'x'
This modifies the value of $var no matter what scope it happens to be in. You need not know its scope; only that it does in fact already exist. To use the OP's example:
$array=#("g")
function foo()
{
([ref]$array).Value += "h"
Write-Host $array
}
& {
([ref]$array).Value +="s"
Write-Host $array
}
foo
Write-Host $array
Produces:
g s
g s h
g s h
Explanation:
([ref]$var) gets you a pointer to the variable. Since this is a read operation it resolves to the most recent scope that actually did create that name. It also explains the error if the variable doesn't exist because [ref] can't create anything, it can only return a reference to something that already exists.
.value then takes you to the property holding the variable's definition; which you can then set.
You may be tempted to do something like this because it sometimes looks like it works.
([ref]$var) = "New Value"
DON'T!!!!
The instances where it looks like it works is an illusion because PowerShell is doing something that it only does under some very narrow circumstances such as on the command line. You can't count on it. In fact it doesn't work in the OP example.

Variable scoping in PowerShell

A sad thing about PowerShell is that function and scriptblocks are dynamically scoped.
But there is another thing that surprised me is that variables behave as a copy-on-write within an inner scope.
$array=#("g")
function foo()
{
$array += "h"
Write-Host $array
}
& {
$array +="s"
Write-Host $array
}
foo
Write-Host $array
The output is:
g s
g h
g
Which makes dynamic scoping a little bit less painful. But how do I avoid the copy-on-write?
The PowerShell scopes article (about_Scopes) is nice, but too verbose, so this is quotation from my article:
In general, PowerShell scopes are like .NET scopes. They are:
Global is public
Script is internal
Private is private
Local is current stack level
Numbered scopes are from 0..N where each step is up to stack level (and 0 is Local)
Here is simple example, which describes usage and effects of scopes:
$test = 'Global Scope'
Function Foo {
$test = 'Function Scope'
Write-Host $Global:test # Global Scope
Write-Host $Local:test # Function Scope
Write-Host $test # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 0) # Function Scope
Write-Host (Get-Variable -Name test -ValueOnly -Scope 1) # Global Scope
}
Foo
As you can see, you can use $Global:test like syntax only with named scopes, $0:test will be always $null.
You can use scope modifiers or the *-Variable cmdlets.
The scope modifiers are:
global used to access/modify at the outermost scope (eg. the interactive shell)
script used on access/modify at the scope of the running script (.ps1 file). If not running a script then operates as global.
(For the -Scope parameter of the *-Variable cmdlets see the help.)
Eg. in your second example, to directly modify the global $array:
& {
$global:array +="s"
Write-Host $array
}
For more details see the help topic about_scopes.
Not just varibles. When this says "item" it means variables, functions, aliases, and psdrives. All of those have scope.
LONG DESCRIPTION
Windows PowerShell protects access to variables, aliases, functions, and
Windows PowerShell drives (PSDrives) by limiting where they can be read and
changed. By enforcing a few simple rules for scope, Windows 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:
- An item you include in a scope is visible in the scope in which it
was created and in any child scope, unless you explicitly make it
private. You can place variables, aliases, functions, or Windows
PowerShell drives in one or more scopes.
- An item that you created within a scope can be changed only in the
scope in which it was created, unless you explicitly specify a
different scope.
The copy on write issue you're seeing is because of the way Powershell handles arrays. Adding to that array actually destroys the original array and creates a new one. Since it was created in that scope, it is destroyed when the function or script block exits and the scope is disposed of.
You can explicitly scope varibles when you update them, or you can use [ref] objects to do your updates, or write your script so that you're updating a property of an object or a hash table key of an object or hash table in a parent scope. This does not create a new object in the local scope, it modifies the object in the parent scope.
While other posts give lots of useful information they seem only to save you from RTFM.
The answer not mentioned is the one I find most useful!
([ref]$var).value = 'x'
This modifies the value of $var no matter what scope it happens to be in. You need not know its scope; only that it does in fact already exist. To use the OP's example:
$array=#("g")
function foo()
{
([ref]$array).Value += "h"
Write-Host $array
}
& {
([ref]$array).Value +="s"
Write-Host $array
}
foo
Write-Host $array
Produces:
g s
g s h
g s h
Explanation:
([ref]$var) gets you a pointer to the variable. Since this is a read operation it resolves to the most recent scope that actually did create that name. It also explains the error if the variable doesn't exist because [ref] can't create anything, it can only return a reference to something that already exists.
.value then takes you to the property holding the variable's definition; which you can then set.
You may be tempted to do something like this because it sometimes looks like it works.
([ref]$var) = "New Value"
DON'T!!!!
The instances where it looks like it works is an illusion because PowerShell is doing something that it only does under some very narrow circumstances such as on the command line. You can't count on it. In fact it doesn't work in the OP example.