How to export and import environment variables in windows?

WindowsEnvironment VariablesWindows Xp

Windows Problem Overview


I found it is hard to keep my environment variables sync on different machines. I just want to export the settings from one computer and import to other ones.

I think it should be possible, but don't know how to do it. Can anyone help me? Thanks.

Windows Solutions


Solution 1 - Windows

You can use RegEdit to export the following two keys:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

HKEY_CURRENT_USER\Environment

The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.

Solution 2 - Windows

I would use the SET command from the command prompt to export all the variables, rather than just PATH as recommended above.

C:\> SET >> allvariables.txt

To import the variablies, one can use a simple loop:

C:\> for /F %A in (allvariables.txt) do SET %A

Solution 3 - Windows

To export user variables, open a command prompt and use regedit with /e

Example :

regedit /e "%userprofile%\Desktop\my_user_env_variables.reg" "HKEY_CURRENT_USER\Environment"

Solution 4 - Windows

Combine @vincsilver and @jdigital's answers with some modifications,

  1. export .reg to current directory
  2. add date mark

code:

set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%

regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output would like:

global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg

Solution 5 - Windows

You can get access to the environment variables in either the command line or in the registry.

Command Line

If you want a specific environment variable, then just type the name of it (e.g. PATH), followed by a >, and the filename to write to. The following will dump the PATH environment variable to a file named path.txt.

C:\> PATH > path.txt

Registry Method

The Windows Registry holds all the environment variables, in different places depending on which set you are after. You can use the registry Import/Export commands to shift them into the other PC.

For System Variables:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

For User Variables:

HKEY_CURRENT_USER\Environment

Solution 6 - Windows

My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat file and put in it:

@echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"

This creates environment-backup.reg which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)

Solution 7 - Windows

Here is my PowerShell method

gci env:* | sort-object name | Where-Object {$_.Name -like "MyApp*"} | Foreach {"[System.Environment]::SetEnvironmentVariable('$($_.Name)', '$($_.Value)', 'Machine')"}

What it does

  1. Scoops up all environment variables
  2. Filters them
  3. Emits the formatted PowerShell needed to recreate them on another machine (assumes all are set at machine level)

So after running this on the source machine, simply transfer output onto the target machine and execute (elevated prompt if setting at machine level)

Solution 8 - Windows

A PowerShell script based on @Mithrl's answer

# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date

mkdir -Force $PWD\env_exports | Out-Null

regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Solution 9 - Windows

Not being satisfied with answers from 12 years ago I've approached this a little differently. This approach could work with Win OS flavors older than Win 8 by using SET instead of SETX which is when SETX began being used.

> NOTE:
> Be sure to tune the RegEx for your preferred editor to achieve desired > results. For RegEx specific questions please seek help from various > sources including tutorials available from here. I'm using Sublime Text 4 for search and replace RegEx examples.

> WARNING:
I would like to point out that following this process > blindly with copy and paste will most likely clobber existing settings > with the source data extracted. It DOES NOT merge the two sets of > data. That is your responsibility and I take no responsibility for > any damage that may result. Additionally, you should take time to > remove settings from the extracted env variables that pose issues or > no value such as changed paths and different hardware metrics such as > CPU core counts.

This approach avoids mixing System env variables with User env variables which a handful of previous answers are plagued with.

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment">>SystemEnvVariablesSourceMachine.txt
reg query "HKEY_CURRENT_USER\Environment">>UserEnvVariablesSourceMachine.txt

Clean up the files that were just created! Import success depends on this! Use a RegEx capable editor and use the following search and replace:

> NOTE: Some RegEx engines/tools require use of the $ character to > represent backreference in the Replace Pattern. If your not getting > the expected results in search and replace give that a try.

Search Pattern:

(?:\A\r?\n|^HKEY_CURRENT_USER\\Environment\r?\n?|^HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\r?\n?|^\r?\n$|\r?\n\Z)

Replace Pattern (Literally Empty):

Literally Empty

and then

Search Pattern:

^\s+(.*?)\s{4}\w+\s{4}(.*?)$

Replace Pattern:

\1=\2

Its strongly advised you take a moment to do the same steps above on the destination machine using these file names:

SystemEnvVariablesDestinationMachine.txt
UserEnvVariablesDestinationMachine.txt

This also will serve as a backup for the upcoming import.

Once the DestinationMachine versions of the files are cleaned up its time to make a copy. Copy of each of the DestinationMachine files and name them something like:

SystemEnvVariablesFinalMerge.txt
UserEnvVariablesFinalMerge.txt

We're not done yet, that's just a version of the file you can feel safe to edit. Leave the DestinationMachine version of the files alone. Consider them a backup.

Next we will merge the SourceMachine files into the FinalMerge files. This provides a means to manual review for cleanup of duplicates and bad data followed by a final output. There are plenty of ways to do this, but the easiest way I've used is to prepare the data for comparison, then compare and merge, and then reassemble the data back so that its importable.

Apply this search and replace RegEx pattern to each Source and FinalMerge file:

Search Pattern:

(^\w+=|.*?(?:;|$))

Replace Pattern:

\1\n

Then compare each Source to FinalMerge using a diff tool such as Beyond Compare 4, Meld, or Winmerge. My personal favorite is Beyond Compare 4. Keep in mind the data at this time may not be sorted so you can take care at this time to sort the data taking care not to mix up variables from key to value structure. How to use those tools is out of scope here. Delete env variables that you do not wish to import at this time from the FinalMerge version of the file.

Once you're satisifed with the merge with cleanup applied save the changes in the FinalMerge files then restore the key to value mapping with the following RegEx pattern:

Search Pattern:

(.)$\r?\n

Replace Pattern:

\1

Then on the destination machine import the variables with powershell:

Get-Content .\UserEnvVariablesFinalMerge.txt | ForEach-Object {
    $envVarDataSplit = $($_).split("=")
    if($($envVarDataSplit).count -gt 0)
    {
        Write-Output "Key: $($envVarDataSplit[0]) ~ Value: $($envVarDataSplit[1])"
        SETX $envVarDataSplit[0] "$($envVarDataSplit[1])"
    }
}

> NOTE:
Run powershell as administrator for this to succeed or you will > get an error.

Get-Content .\SystemEnvVariablesFinalMerge.txt | ForEach-Object {
    $envVarDataSplit = $($_).split("=")
    if($($envVarDataSplit).count -gt 0)
    {
        Write-Output "Key: $($envVarDataSplit[0]) ~ Value: $($envVarDataSplit[1])"
        SETX $envVarDataSplit[0] "$($envVarDataSplit[1])" /M
    }
}

> NOTE:
If you encounter an error here its likely due to a need to > escape a character. You'll need to either manually enter that env > variable or figure out the proper escaped character sequence to get > around it.

If things have gone horribly wrong you should be able to revert to your DestinationMachine versions of the env variables using the previous command with the backup.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmax_yView Question on Stackoverflow
Solution 1 - WindowsjdigitalView Answer on Stackoverflow
Solution 2 - WindowsKushal PaudyalView Answer on Stackoverflow
Solution 3 - WindowsvincsilverView Answer on Stackoverflow
Solution 4 - WindowsMithrilView Answer on Stackoverflow
Solution 5 - WindowsGavin BunneyView Answer on Stackoverflow
Solution 6 - WindowspatricknelsonView Answer on Stackoverflow
Solution 7 - WindowsfiatView Answer on Stackoverflow
Solution 8 - WindowsPhani RithvijView Answer on Stackoverflow
Solution 9 - WindowsSn3akyP3t3View Answer on Stackoverflow