Copyget-content test.env | foreach {
    $name, $value = $_.split('=')
    set-content env:\$name $value
}

assuming you mean "set one environment variable per line in the file".

Answer from TessellatingHeckler on Stack Overflow
🌐
GitHub
github.com › stopthatastronaut › poshdotenv
GitHub - stopthatastronaut/poshdotenv: Simple PowerShell Module to load from .env files · GitHub
A simple PowerShell module enabling loading of .env files into a PowerShell session. Takes inspiration from the node norm of env files. It simply picks up your key value pairs from .env, and loads them into transient environment variables.
Starred by 27 users
Forked by 7 users
Languages   PowerShell 98.6% | Shell 1.4%
Discussions

How to invoke one PS1 from another and pass environment variables that persist?
you can 'dot source' scripts in powershell ... which effectively merges the script into the current execution ... or you can just execute a script in a subshell/process with a copy of the parent environment. The subshell will pick up environment variables of the parent ... but the parent won't see any created by the child process ... so if you're doing that then it won't work. Dot sourcing pulls the script into the current process and hence the same environment so the 'parent' will see any new environment variables (and 'global' scope variables too) It's better to use script parameters rather than environment variables ... as there is a closer affinity to the execution with parameters and the user of the script informed if parameters are required and not passed in ... environment variables can be forgotten and just default to $null if they don't actually exist ... you could also have done this with your bat files. More on reddit.com
🌐 r/PowerShell
15
6
December 28, 2023
Setting Windows PowerShell environment variables - Stack Overflow
I have found out that setting the ... settings. How do I change the environment variables for PowerShell (v1)? ... I want to make my changes permanent, so I don't have to set it every time I run PowerShell. Does PowerShell have a profile file?... More on stackoverflow.com
🌐 stackoverflow.com
env and environment variables in Powershell
$env is a powershell object just like $true. If you want to set an environment variable there's 2 normal ways to do it, one using $env, the second using [Environment]::SetEnvironmentVariable Using $env will only set the variable for the current powershell process, whereas using [Environment]::SetEnvironmentVariable you can set it for different areas (process, user, or machine). When you do $INCLUDE you're not setting an environment variable, you're just creating a variable called $INCLUDE. see http://technet.microsoft.com/en-us/library/ff730964.aspx More on reddit.com
🌐 r/PowerShell
5
8
December 7, 2014
How can I constantly source a file with environment variables?
The borderline-insane way (untested, because borderline-insane): PROMPT_COMMAND='source /path/to/.env' If PROMPT_COMMAND is already set to something, turn it into an array instead: PROMPT_COMMAND=("$PROMPT_COMMAND" 'source /path/to/.env') The reason I strongly discommend this approach (and your current DEBUG trap method too): someone might come along and add Something Really Bad/Stupid to your .env, then the next time you hit Enter in any of your terminals, and realize why the prompt is taking so long to appear, it may be too late to recover any of your recent work. That someone might even be you, nursing a hangover... A Safer Approach direnv . I use it on all my systems to help keep my environment sane as I cd from one workspace to another, automatically setting and unsetting vars (and optionally running other commands) as needed. The main upside: it's paranoid about changes in .envrc files, precisely because they're shell scripts to be sourced, not config files to be read. Any change in a directory's controlling .envrc requires you to run direnv allow . to accept it, so the above disaster scenario should not happen, unless you're nursing a hangover... You don't say whether your .env files are meant to be applied when you're somewhere in the directory hierarchy below it, or you want a single, say, ~/.env file to be applied no matter what directory you're in. direnv works on the former model, which I've found to be more useful than a "One File To Rule Them All (directories)" policy. More on reddit.com
🌐 r/bash
4
4
March 7, 2024
🌐
GitHub
gist.github.com › coltfred › 70f7c13ad8c6090e72e1775df90b7ee4
Load env files on windows in powershell. · GitHub
Load env files on windows in powershell. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
github.com › rajivharris › Set-PsEnv
GitHub - rajivharris/Set-PsEnv: PowerShell DotEnv Loader · GitHub
This is a simple script to load the .env file to process environment from the current directory.
Starred by 50 users
Forked by 11 users
Languages   PowerShell
🌐
Medium
bennett4.medium.com › windows-alternative-to-source-env-for-setting-environment-variables-606be2a6d3e1
Windows Alternative to “source .env” for Setting Environment Variables | by Matthew Bennett | Medium
December 7, 2020 - The existing method for setting environment variables was to call source .env before any command in package.json that needed the environment variables to be set. ... I received this same response when running this command in Windows PowerShell, Command Prompt, and Git Bash. source is a shell command that reads and executes the contents of a file (generally a set of commands) within the current shell context.
🌐
PowerShell Gallery
powershellgallery.com › packages › dotenv › 0.1.0
PowerShell Gallery | dotenv 0.1.0
Allows PowerShell to load Environment Variables from a .env file, similarly to node or docker.
🌐
GitHub
gist.github.com › tmeckel › dc9f935beb7a4a20e70dc2c2c9c7b036
Read .env file with PowerShell · GitHub
Read .env file with PowerShell · Raw · Read-DotEnv.ps1 · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_environment_variables
about_Environment_Variables - PowerShell | Microsoft Learn
On macOS, you can add environment variables to the /etc/profile file. When starting PowerShell from another shell, you can define environment variables in the shell-specific initialization files used by non-login shells, such as ~/.bashrc for bash or ~/.zshrc for zsh.
Find elsewhere
🌐
Petri
petri.com › home › powershell › powershell set environment variable – a step-by-step guide
PowerShell Set Environment Variable - A Step-By-Step Guide | Petri
May 5, 2025 - In this step-by-step guide, we’ll explore what environment variables are, their scopes, and how to set environment variables using PowerShell. Environmental variables often contain critical configuration information for the operating system and its modules, such as current user information, directory paths, or the location of certain core files for the operating system to function.
🌐
Reddit
reddit.com › r/powershell › how to invoke one ps1 from another and pass environment variables that persist?
r/PowerShell on Reddit: How to invoke one PS1 from another and pass environment variables that persist?
December 28, 2023 -

So if you've seen my username more than once on this platform you'll undoubtedly be familiar with my ecosystem of BATs, which I use to automate various functions on my home network, and which greatly speed the creative work that I do.

Many have rightly pointed out that PS1s would be a far better choice, and while I've agreed wholeheartedly, the simple fact is I haven't had the time to invest (yet) in converting to PS1s. The good news here is that 99% of these BATs are already formatted to use Powershell syntax, so the actual operations being performed I don't think will change very much.

But now comes the key piece that's been holding me back: a lot of the operations I use involve being able to set local and environmental variables like so:

@echo off & setlocal

set "sourceDir=E:\SomeDir"

And reading them like so:

$sourceDir=$Env:sourceDir

And I'm a little unclear on how to make this work between PS1s. Here's what a typical operation looks like, with what I call a "super BAT" that backs up and cleans content from my main media drive:

  • Double click the starter BAT

  • The starter BAT file begins with defining three variables, before calling a series of other BATs, which we'll call "parent BATs" because they contain lists of "child BATs" that actually run operations

  • The parent BATs don't have variable definitions of their own, they just pass along the values they got from the starter BAT (with one exception--at one point the source and destination directories get swapped)

  • The child BATs inherit the values from the starter BAT, and run a bunch of operations in sequence, deleting temporary and junk files and copying files and folders all over the place

With this setup, I only have to define the first variables, and the BATs do the rest. The idea is to have a common set of commands that I can run, so I'm not re-creating the wheel every time I need to do something. All instances where I need to copy files using ROBOCOPY are defined in one BAT; all instances when I need to use MOVE-ITEM for the same task (because it can rename and ROBOCOPY can't as far as I know) are defined in another, but they're all set up to accept environmental variables supplied by the BATs I actually interact with.

/And MOVE-ITEM is just one...I have 46 child BATs in all to do various things, that I invoke in varying combinations to do specific things. I have commands that clear folders of everything but the newest file, to clear folders of ALL files, several variants that create new folders for different things, commands that identify and delete the largest or oldest or smallest files in a group...I could keep going, but you get the idea.

Combined, they help me keep my system clean and well-organized.

So for instance:

If the operation I want to launch is to do a full cleanup and backup of my main drive, this is what the process actually looks like:

  • ___SUPERBAT__Full Operation_E-WSV.BAT

    • defines three variables

    • calls "Subroutines\___SUPERBAT Operation_001_Clear Debris.bat"

      • "___SUPERBAT Operation_001_Clear Debris.bat" defines search terms, then calls "call "%~dp0\Find and Delete Folders.bat"

      • "Find and Delete Folders.bat" inherits the values that came from the "full operation" BAT at the beginning plus the search terms from "001_Clear Debris.bat," and does its thing

      • "___SUPERBAT Operation_001_Clear Debris.bat" defines search terms, then calls "call "%~dp0\Find and Delete Files.bat"

      • "Find and Delete Files.bat" inherits the values that came from the "full operation" BAT at the beginning plus the search terms from "001_Clear Debris.bat," and does its thing

    • once all operations from SUPERBAT 001 are done, "___SUPERBAT__Full Operation_E-WSV.BAT" calls "Subroutines\___SUPERBAT Operation_002_Copy to H.bat", which invokes a different set of child BATs, which work off the same variables as SUPERBAT 001...

...and so on and so forth. For this one operation, there are a total of six numbered SUPERBAT files, and between them they invoke almost two dozen BATs...but because of how I've got it all set up, everything runs off just those three variables at the start.

So now my question is, how do I re-create this with Powershell scripts? I can convert all my child BATs to PS1s with no problem, but I need to key them to accept environmental variables like I did the BATs, and I need said variables to persist throughout the entire series of operations launched from the "Full Operation" file at the very beginning.

Does this make sense?

Top answer
1 of 7
7
you can 'dot source' scripts in powershell ... which effectively merges the script into the current execution ... or you can just execute a script in a subshell/process with a copy of the parent environment. The subshell will pick up environment variables of the parent ... but the parent won't see any created by the child process ... so if you're doing that then it won't work. Dot sourcing pulls the script into the current process and hence the same environment so the 'parent' will see any new environment variables (and 'global' scope variables too) It's better to use script parameters rather than environment variables ... as there is a closer affinity to the execution with parameters and the user of the script informed if parameters are required and not passed in ... environment variables can be forgotten and just default to $null if they don't actually exist ... you could also have done this with your bat files.
2 of 7
4
You don’t use environment variables for this in PowerShell—just one example of PS being more flexible than BAT. Define the variables in a .ps1 file, or if you want, in a .psd1 file, which is a PowerShell data file. PowerShell data files support limited code, being intended for configs only. They’re something of a friendlier json format. The shortest distance in your case however will be to use .ps1 files. Just dot source your config file to load the variables into the parent script’s scope. Any script the parent script calls will have these variables in their scope. The .psd1 file would take a couple more steps and would fit better into an optimized structure that’s more idiomatic of PowerShell and probably isn’t immediately ready coming from BAT. Well, in fact PowerShell supports multiple alternative formats of config files including json or string data (a data block or file containing lines of var = value). It just depends on whether you want to use a config file in the first place and the scenarios you wish to use it in. Again the easiest is just a .ps1 file that you dot source.
🌐
w3tutorials
w3tutorials.net › blog › how-do-i-read-a-env-file-from-a-ps1-script
How to Read a .env File in a PowerShell (.ps1) Script: Step-by-Step Guide — w3tutorials.net
Use the example above or customize it with your variables. Save it as .env (note the leading dot—this makes it a hidden file on Unix-like systems, but Windows will still recognize it). Create a new PowerShell script (e.g., Load-Env.ps1) to parse the .env file.
🌐
Opensource.com
opensource.com › article › 19 › 9 › environment-variables-powershell
Environment variables in PowerShell | Opensource.com
You can view all environment variables set on your system with the Get-ChildItem command from within the Env: drive. The list is long, so pipe the output through out-host -paging to make it easy to read: PS> Get-ChildItem | out-host -paging LOGNAME seth LS_COLORS rs=0:mh=00:bd=48;5;232;38;5; MAIL /var/spool/mail/seth MODULEPATH /etc/scl/modulefiles:/etc/scl/modulefiles MODULESHOME /usr/share/Modules OLDPWD /home/seth PATH /opt/microsoft/powershell/6:/usr/share/Modules/bin PSModulePath /home/seth/.local/share/powershell/Modules PWD /home/seth [...]
🌐
Configu
configu.com › home › setting environment variables in powershell: a practical guide
Setting Environment Variables in PowerShell: A Practical Guide - Configu
January 17, 2025 - Export them to a JSON or CSV file that can be easily imported if needed. This can prevent accidental loss of critical configurations and provides an easy way to restore setups. Use PowerShell profiles for persistent custom settings: For user-specific, persistent environment variables, configure PowerShell profiles (e.g., $PROFILE.CurrentUserAllHosts).
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-set-environment-variables-using-powershell
How to Set environment variables using PowerShell?
To set the environmental variable using PowerShell you need to use the assignment operator (=). If the variable already exists then you can use the += operator to append the value, otherwise, a new environment variable will be created.
🌐
Microsoft Certified Professional Magazine
mcpmag.com › articles › 2019 › 03 › 28 › environment-variables-in-powershell.aspx
How To Work with Environment Variables in PowerShell -- Microsoft Certified Professional Magazine Online
March 28, 2019 - PS C:\> Get-ChildItem -Path Env:\ Name Value ---- ----- ADPS_LoadDefaultDrive 0 ALLUSERSPROFILE C:\ProgramData API_Location_ComputerVision eastus2 API_SubscriptionKey_Compute... e937bbf5cea841728c64c4eda00e1aca APPDATA C:\Users\Administrator.FUSIONVM\AppData\Roaming CommonProgramFiles C:\Program Files\Common Files CommonProgramFiles(x86) C:\Program Files (x86)\Common Files CommonProgramW6432 C:\Program Files\Common Files <SNIP>
🌐
Netwrix
netwrix.com › home › resources › blog › powershell environment variables
PowerShell Environment Variables
August 25, 2025 - PowerShell environment variables store system and user configuration as key-value pairs accessible across processes and scripts. They can be listed with Get-ChildItem Env:, accessed with $Env: , modified with Set-Item or [Environment]::SetE...