This is how PowerShell Variables are designed to work. Variables your scripts or functions set only last as long as they're running, when they end, their values go away.

In what you're doing today, you're changing the $global scope variable but not running a script or function. You're effectively in the global scope already.

In order to use those nested scopes, you need to run a script or function, like this script below, called scratch.ps1

#script inherited the previous value

"script: current favorite animal is $MyFavoriteAnimal, inherited"

#now setting a script level variable, which lasts till the script ends
$MyFavoriteAnimal = "fox"

"script: current favorite animal is $MyFavoriteAnimal"

function GetAnimal(){
   #this function will inherit the variable value already set in the script scope
   "function: my favorite animal is currently $MyFavoriteAnimal"

   #now the function sets its own value for this variable, in the function scope
   $MyFavoriteAnimal = "dog"

   #the value remains changed until the function ends
   "function: my favorite animal is currently $MyFavoriteAnimal"
}

getAnimal

#the function will have ended, so now the script scope value is 'back'
"script: My favorite animal is now $MyFavoriteAnimal"

To access this functionality, you'll need to use scripts or functions.

Answer from FoxDeploy on Stack Overflow
🌐
Varonis
varonis.com › blog › powershell-variable-scope
PowerShell Variable Scope Guide: Using Scope in Scripts and Modules
October 13, 2022 - PowerShell’s automatic and preference ... your PowerShell profile are also available in the global scope. Script: This is the scope created when you run a script....
Discussions

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function - Stack Overflow
I am seriously so annoyed by this powershell weirdness! Seems to me that declaring a variable in a top level (not in function) should make it global and would make sense to me! And yes it does but only in ISE! So you write code and then it frikin breaks in the console, because you didn't use $global: when declaring a variable. How can be variables declared in the main script ... More on stackoverflow.com
🌐 stackoverflow.com
Global vs Script scope
The best practice is always to use the smallest parent scope that works. In this case, it's script scope. Global scope is shared by all scripts and modules so it's easy to accidentally write over another variable's value in global scope. To refer to a variable in script scope, use a scope modifier, for example, to reference $myArray in script scope, use $script:myArray. More on reddit.com
🌐 r/PowerShell
3
2
September 2, 2015
PowerShell — Understanding Scope - by Rod Trent - myITforum
When working with PowerShell scripts and modules, understanding variable scope is paramount to writing efficient, reliable, and maintainable code. However, the distinctions between global, script, and local scopes often lead to confusion. More on myitforum.substack.com
🌐 myitforum.substack.com
May 15, 2025
Creating New Global Variables using New-Variable
Any reason you don't just pass your variable into the function as a parameter? More on reddit.com
🌐 r/PowerShell
12
17
January 3, 2023
🌐
Reddit
reddit.com › r/powershell › help me understand when a var is global vs when it's not.
r/PowerShell on Reddit: Help me understand when a var is global vs when it's not.
February 3, 2023 -

Edit: Thanks for the explainations. My confusion was a misunderstanding of import-modules when I really should be dot-sourcing my functions for the scripts that I write to keep everything within the same scope and have constants that only need to be declared once but used heavily throughout the entire script. So by dot sourcing, I can have the vars that I need to be "global" (I realize how I'm using that word and really mean within same scope) without having to explicitly pass that var each time as a parameter.

Original:

So I'm having a lil bit of confusion around when my vars are global in scope vs when they aren't. So say I'm writing a called "Script.ps1" and I create a module file and call that "Logger.psm1" and use an import-module statement in Script.ps1. Logger.psm1 has a custom function called write-log.

So now say I declare a var in Script.ps1. This var is something that is a constant and will never change. Like a logging directory. Now we have the following files:

Script.ps1:

import-module ".\Logger.psm1"

$LogDirectory = "Some\File\Path"

write-log -message "Test Message"

Logger.psm1:

function Write-Log {
    param (
        $message
    )
    $messsage | Out-file -path "$LogDirectory\logfile.log"
}

In this setup I expect $LogDirectory to be a global var that is accessible by the module I imported and calling from Script.ps1. But the behavior I see is $LogDirectory isn't treated as a global var. Instead I have to actively declare $LogDirectory as a global using $global:Logdirectory for the module to see it. Otherwise I have to add it as a parameter.

So few questions:

  • Why is this?

  • Does the module have a separate global scope from the ps1 script that imported it?

  • What's the best practice for accomplishing something like this? I have another script that I think is suffering from a similar issue.

Top answer
1 of 5
10
Unless you explicitly declare a variable with a different scope, a variable will only be available for use where it's declared. E.g., if declared in a cmdlet/function then it can only be used by what's contained within that cmdlet/function. Creating a function within a cmdlet does not let you use the variables declared in the cmdlet in the function and vice versa--you would have to pass values through params. Declaring something as global allows it to be used by anything else running within the runspace and it persists after the cmdlet/function terminates. In your example, I would just add a log directory parameter to write-log. This would make your function more flexible since you could change where something gets logged on the fly instead of being stuck only being able to write to a single location.
2 of 5
4
Perhaps the way I use it can provide an example. I wrote a function to capture the nested structure of the groups in my org. It loops through the membership and when it finds a group, it makes a call back to itself. Basically, something like… Show-nestingchart When it finds a nested group it calls to Show-nestingchart, basically itself, to loop through that membership. It returns an output like this: Member. Member. Member. Member. NestedGroup\member. NestedGroup\member. NestedGroup2\member. NestedGroup3\member. NestedGroup\anothergroup\member. Each time it calls to itself, each instance has variables scoped locally to it. The results are written to a $global:results held in the 1st instance.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_scopes
about_Scopes - PowerShell | Microsoft Learn
July 22, 2024 - The global scope is the root parent scope in a runspace. Local: The current scope. The local scope can be the global scope or any other scope. Script: The scope that's created while a script file runs.
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › powershell global variables: a comprehensive guide
PowerShell Global Variables: A Comprehensive Guide - SharePoint Diary
October 9, 2025 - Because they have a wider scope, global variables are suitable for storing data that different functions or scripts need to share. In PowerShell, variable scope relates to where a variable can be accessed.
🌐
Adam the Automator
adamtheautomator.com › powershell-scopes
PowerShell Scopes: Understanding Variable Scope
January 27, 2026 - Now the script scope is scope zero and the global scope is scope one. Scopes are numbered This process repeats for as many scopes as you have where the local scope is 0. Scopes are dynamically numbered by scope hierarchy. As mentioned earlier, when you launch a PowerShell session, PowerShell creates some items for you in the global scope. These items can be functions, variables, aliases, or PSDrives.
Find elsewhere
🌐
Reddit
reddit.com › r/powershell › global vs script scope
r/PowerShell on Reddit: Global vs Script scope
September 2, 2015 -

I'm still fairly new to the scripting scene and I've run into a bit of bother with one of my latest scripts. There is a function in the script which passes string values into an array. I would like to call this function numerous times so that the array keeps growing with more and more objects. At the end I want to pass the array on to a different part of my script.

I already know that using the default Local scope for the array won't work, but I want to know which of the Global or Script scope should I use?

🌐
Substack
myitforum.substack.com › p › powershell-understanding-scope
PowerShell — Understanding Scope - by Rod Trent - myITforum
May 15, 2025 - To mitigate issues, limit the use of global scope to cases where persistence across scripts is necessary. Definition: The script scope applies specifically to variables and commands defined within a single PowerShell script file.
Top answer
1 of 1
2

From https://technet.microsoft.com/en-us/library/hh847849.aspx

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.

so you could use $Global:x = ... to set it.

Powershell scripts are often copied and pasted in blocks to implement functionality, and often methods are written to be used by multiple scripts. By restricting assignment to the defining scope for a variable, you ensure that even if two pasted blocks of code use the same variable name, they cannot improperly change data that the other block depends on, without explicitly stating that they wish to do so. This helps to make blocks more modular, and helps to identify unintentional name collisions.

Edit:

a note on powershell scope: Powershell cascades scopes, so the local scope always contains objects defined in ancestor scopes (parent, grantparent, global, etc). That means that a variable defined globally or in a parent stack frame (a function calling a function) are always accessible, whereas objects defined in child scopes are not. In this case, the only restriction is that a child scope cannot modify a parent scopes value, unless that scope is defined explicitly.

From: https://technet.microsoft.com/en-us/library/hh847849.aspx

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.


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.
🌐
Enterprise DNA
blog.enterprisedna.co › powershell-global-variable
Powershell Global Variable: Explained With Examples – Master Data Skills + AI
Script: The variable is accessible ... scope, and it is not inherited by any child scope. A PowerShell global variable is a variable that is accessible across all scripts, functions, or cmdlets within the current session....
🌐
SPGuides
spguides.com › powershell-global-variable
How to Use PowerShell Global Variables?
March 26, 2025 - Now, any script or function can access the $domainController variable without the need to pass it as a parameter or redefine it. ... To set a global variable in PowerShell, you can use the $global: prefix followed by the variable name. This ensures that the variable is accessible from anywhere within the current PowerShell session.
🌐
SS64
ss64.com › ps › syntax-scopes.html
Define the Scope of a variable. - PowerShell
To specify the scope of a new variable, alias, or function, prefix the name with a scope modifier: $global:DemoVar = "hello" $script:DemoVar = "world" $private:DemoVar = "world" function global:DemoFunc {...}
🌐
Powershellbyexample
powershellbyexample.dev › post › variable-scopes
Scopes | PowerShell By Example
The local scope is relative to whatever context the code runs in at the time. To define an item local you use the local: modifier. By default the scope of a variable is the Local scope. ... Items in the global scope are available everywhere.
🌐
How-To Geek
howtogeek.com › home › files › how scopes affect powershell scripts
How Scopes Affect PowerShell Scripts
November 26, 2014 - In batch scripts, changes to environment variables have a global impact to the current session by default. For PowerShell, the exact opposite is true because scopes are used to isolate a script's modifications.
🌐
Rahul Singla
rahulsingla.com › home › powershell – assigning global variable inside a function does not actually over-write the global one
PowerShell - Assigning Global variable inside a function does not actually over-write the global one - Rahul Singla
January 10, 2023 - Assigning a global variable inside a PowerShell function does not actually change the global variable. It rather creates a local variable with the same name.
🌐
Reddit
reddit.com › r/powershell › creating new global variables using new-variable
r/PowerShell on Reddit: Creating New Global Variables using New-Variable
January 3, 2023 -

EDIT: Solved. I figured it out myself actually. I add -Scope "Global". See example:

New-Variable -Name $newVar -Value $newVal -Force -Scope "Global"

The result ends up being:

$MyDomain
www.myDomain.net
$global:MyDomain
www.myDomain.net

Basically, a local AND global variable end up getting set.

***Original Post***

I have something like this outside of any function:

$global:MyDomain=""

The rest is inside a function.

I then read a file called Info.txt. The following represents a single line as an example:

global.MyDomain:www.myDomain.net

I have code which will split the previous line and get the values:

$myVar
global.MyDomain
$myVal
www.myDomain.net

The period found in $myVar is replaced with a colon:

$myVar=$myVar.Replace(".",":")
$myVar
global:MyDomain

The idea is to create a new variable, based on the contents of $myVar. Thus, the new variable would be called $global:MyDomain, where it would be equal to www.myDomain.net. I use this code:

New-Variable=-Name $newVar -Value $newVal -Force

Here's the problem:

If I take $global. out of the line, thus making it a local variable, it will work just fine. As a global variable, it will not. It has to do somehow with New-Variable.

Can I create a new global variable using New-Variable or is there another way to do so which will work for global variables?

🌐
PowerShell Forums
forums.powershell.org › powershell help
Must variable be global for Export-ModuleMember -Variable? - PowerShell Help - PowerShell Forums
December 4, 2022 - Suppose within *.psm1 module file you declare a variable like this: $Variable1 = 0 New-Variable -Name Variable2 -Value 1 This are by default script scope variables. Can I export script scope variable now with: Export…
🌐
PowerShell Test-Path
powershellfaqs.com › powershell-global-variables
PowerShell Global Variables [With Examples]
September 5, 2024 - PowerShell global variables are variables that are accessible from any scope within the current session, allowing for data sharing across scripts, functions, and cmdlets. Declared using the $global: prefix, these variables are ideal for storing information like API keys or configuration settings ...
🌐
IT-Connect -
it-connect.tech › home › the scope of variables
La portée des variables avec PowerShell - Cours en ligne
March 13, 2025 - By default, a variable is accessible throughout the script in which it was declared, and even beyond since it is accessible in the entire PowerShell session, but you may not want this for all variables. PowerShell supports 3 different types of scope for its variables: global, local and script.