142

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.

jww
  • 97,681
  • 90
  • 411
  • 885
max_y
  • 1,423
  • 2
  • 10
  • 4

9 Answers9

155

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.

Vivek
  • 11,938
  • 19
  • 92
  • 127
jdigital
  • 11,926
  • 4
  • 34
  • 51
  • 2
    run the program regedit, highlight the keys in question and then use the "file -> export" option so save it as a file – Silvertiger Jun 09 '14 at 13:47
  • the import is done simply with double clicking the .reg file while having admin permissions. – thanos.a May 05 '16 at 10:23
  • 1
    NOTE: This doesn't get all Environment Variables(EV)! I just did a command set path and messed up all my EV. I went to this registry and only the original EV were there. I did a system restore and got all my missing EV back to the PATH var. This registry only holds a few necessary EV, but not any of your program's EV nor any paths you set manually. BEWARE! On a command line: echo path > mybackup.txt or set > mybackup.txt for the whole backup on ALL vars/paths and ALL sys vars/paths. – ejbytes Aug 06 '16 at 10:08
  • 1
    @ejbytes This does copy your global variables that you set but it is probably better to export them with the CLI instead of through the registry. – Alexander May 15 '17 at 20:14
143

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
Carsten Führmann
  • 3,119
  • 4
  • 26
  • 24
Kushal Paudyal
  • 3,571
  • 4
  • 22
  • 30
  • 12
    How do you import back all the exported Env. Vars. from allvariables.txt – Ash Apr 09 '15 at 19:12
  • Very nice. I just lost all my path vars doing a bad path set and had to do a system restore. Luckily I had a recent update as of today earlier. I just did a backup with this command. Nice. That registry solution only holds the original vars, but nothing that "you" (as a programmer say for new builds) created or any new install created. – ejbytes Aug 06 '16 at 10:02
  • 2
    On Windows 7 64-bit, if there are two identically named variables at the User level and the System level, this command gives precedence to the User level variable and omits the System level one. This behavior makes sense, but figured it might be worth a mention in case anyone was expecting the full set from each variable type. – GoldDragonTSU Apr 04 '19 at 15:51
  • 1
    this command did work: `set > "C:\Users\xx\Desktop\envir variable.txt"` – JinSnow May 27 '19 at 04:51
  • Thanks @JinSnow this worked for me. The command by Kushal gave me an "access denied" error. – Azurespot Oct 17 '19 at 21:17
  • 1
    To answer Ash, you can use a simple for loop in the cmd prompt to import back all the variables: `for /F %A in (allvariables.txt) do SET %A` – Gabriel Feb 08 '20 at 09:34
  • This appears to fail when importing paths containing spaces, such as "Program Files". – Lorem Ipsum Jun 07 '21 at 20:53
  • 3
    In Windows 10, when importing, I believe most users will want to use `SETX` rather than `SET` – to make the change permanent. (Not having to import every time a new command window is opened.) – Henke Sep 08 '21 at 13:34
  • 1
    @Henke is correct. Use SETX if you want it to persist. Also, warning that this approach will mash both User and System env variables into a single file on read which it will load from and save that mixed file into the User env variables. If that is not desirable then manually extract System env variables from that mixed file into a separate file and use the /M flag with those to import them as System env variables. – Sn3akyP3t3 Sep 28 '21 at 17:18
22

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"
nevets1219
  • 7,692
  • 4
  • 32
  • 47
vincsilver
  • 221
  • 2
  • 2
16

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
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Mithril
  • 12,947
  • 18
  • 102
  • 153
  • 4
    the **TODAY** variable depends on **%DATE%** which is dependent on how Windows Locale preferences. The above command does not work for India. This works --> _set TODAY=%DATE:~4,2%-%DATE:~7,2%-%DATE:~10,4%_ – Rakesh N Oct 05 '17 at 10:54
7

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
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Gavin Bunney
  • 1,240
  • 1
  • 12
  • 12
5

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 :)

patricknelson
  • 977
  • 10
  • 16
4

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)

fiat
  • 15,501
  • 9
  • 81
  • 103
1

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"
Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60
0

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.

Sn3akyP3t3
  • 656
  • 4
  • 10
  • 23