Setting a System Environment Variable

Introduction

I have recently started to use the excellent Inno Setup utility to create some install scripts for my own applications and discovered there was no way to set a system wide environment variable except by using an external application. SetEnv now supports User and System environment variables.

I began by searching for the Microsoft setex tool but couldn't find it (didn't really try that hard though), so I thought I'd write my own; hence, this article.

Screenshot

System Environment Variables

The method used to create a system wide environment is dependent upon the operating system in use. SetEnv will automatically detect this and use one of the following techniques to create, modify, or delete the environment variables.

Windows 95/98/ME

Under Windows 9x, creating an environment variable requires modifying the user's autoexec.bat file and then executing it (or rebooting) before the variable is recognised by the Operating System.

SetEnv will automatically locate the autoexec.bat file itself (only if the file is on the C:\ or D:\ drives) and then add or modify the selected system variable. The one thing SetEnv will not do is reboot the PC because this should be left up to the user or the Setup Kit (from Inno Setup for example) to choose when to perform the reboot.

Windows XP/2000/2003

Under more modern (in other words, proper) operating systems, such as Windows 2000, XP, and Windows 2003 Server, environment variables are stored in the Registry under the following key:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\
                   Environment

Variables are added by creating a new value under this key or by modifying a value if it already exists. To delete a variable, you simply delete its Registry value, unless you are removing part of an expanded value, such as PATH, in which case you only remove the part you want.

At this point, Windows will not be aware of your changes unless you log off or reboot. To get around this, SetEnv will broadcast a WM_SETTINGCHANGE to all of the windows in the system. This allows other running applications—for example, Explorer.exe—to be notified of your change. If you run SetEnv from a command prompt, this will not update the environment variable for the current DOS window. This is mainly due to the fact that a process (SetEnv) cannot change the environment of its parent (The Command Prompt). However, any new DOS/Command Prompts that you open will show the new variable/value.

Broadcasting this message results in a slight delay (whilst the open windows process it) of around 2-3 seconds, so it may appear that SetEnv has hung. This is not the case.

Using SetEnv

SetEnv is very easy to use and has only a few command line arguments. This section will describe how to use them.

Typing SetEnv at a command prompt and then pressing the Return key will make SetEnv display its usage information, which can be seen in the screen shot at the top of this page.

User environment variables

As of version 1.04, SetEnv also supports User environment variables. If you want SetEnv to either add or delete a User variable, add the -u option to the command line.

Creating a variable

SetEnv can create two types of variable, a simple one that has only a single value such as:

InstallPath = C:\Program Files\Xanya\_Bin

or more complex variables with multiple values. A good example of this is the PATH variable:

PATH = C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Xanya\_Bin

To create a simple variable, just enter in the following command line, obviously substituting your own variable name and value.

SetEnv -a InstallPath "C:\Program Files\Xanya\_Bin"

Similarly, to add a variable with multiple values, you need to type the following command line for each value ensuring you prefix the value with the % character.

SetEnv -a name %value

For example,

SetEnv -a PATH %"C:\Program Files\Xanya\_Bin
SetEnv -a PATH %"C:\Bin

To add a User variable instead of a System one, add the -u option as in the following example:

SetEnv -ua PATH %"C:\Program Files\Xanya\_Bin

Modifying an existing variable

You modify variables in exactly the same way in which you would create them. If you are modifying a multi-value variable and you forget the % prefix to the value, SetEnv automatically will detect that the destination has multiple values and will modify it correctly.

Deleting a variable

To delete a variable, specify the -d option instead of the -a option as in the following example.

SetEnv -d InstallPath

To delete a value from a multi-value variable, you simply enter the following, specifying the value to remove.

SetEnv -d PATH %"C:\Program Files\Xanya\_Bin

As with modifying a multi-value variable, if you forget to specify the % prefix, SetEnv automatically will work this out and delete the specified value only.

To delete a User environment variable, simply add the -u option as follows:

SetEnv -ud PATH %"C:\Program Files\Xanya\_Bin

Running SetEnv from a batch file

SetEnv can be run sucessfully from a batch file. However, a problem was found by David Langford; it occurs when you attempt to specify the expanded variable prefix '%' to a value which contains a drive letter, as in the following example (This is only an issue when running SetEnv from a batch file).

SetEnv -d PATH %C:\Test

The Windows batch file interpreter will interpret the '%' character as prefix to a variable and will replace it with what it believes is the variable, %C:, with the contents of that variable, which of course is nothing. This results in SetEnv being passed a modified value as shown here:

SetEnv -d PATH \Test

This is obviously wrong and SetEnv will not be able to match the value to be removed in the expanded variable. Therefore, it will fail to delete the value from the variable. The workaround is to escape the '%' character with another '%' character. The following example will correctly remove the C:\Test value from the expanded variable, PATH.

SetEnv -d PATH %%C:\Test

History

  • 1.04 (May 30, 2006) - Added support for User environment variables.
  • 1.03 (May 17, 2006) - Updated the article to explain how to use SetEnv from a batch file, after a problem was found by David Langford.
  • 1.03 (Apr 20, 2006) - Bug fix in ProcessWinXP() discovered by attiasr.
  • 1.01 (Nov 15, 2005) - Bug fix in IsWinME() discovered by frankd.
  • 1.00 (Oct 29, 2005) - Initial Public Release.

Bugs

There are no known bugs, but If you do find any, please let me know.



Downloads

Comments

  • Independent content material lets out Some new things surrounding nike shoes that noone is mentioning.

    Posted by moisseenfogma on 05/20/2013 10:06am

    U [url=http://www.nikekutuja.biz/]nike スニーカー[/url] luCws BrjRwb DkcAbg Ggx [url=http://www.nikekutuja.biz/air-jordan空気ヨルダン-c-1.html]air jordan[/url] DhpYcdXhc Tq [url=http://www.nikekutuja.biz/air-maxエアマックス-c-2.html]nike air max[/url] jSlgCwpJcw WzpGzrJfj [url=http://www.nikekutuja.biz/nike-air-force-1ナイキエアフォース-c-4.html]air force[/url] Zzi IqdMmw Kb [url=http://www.nikekutuja.com/]ナイキスニーカー[/url] wKxf EvpBbx FjnFty MbdP [url=http://www.nikekutuja.com/air-jordan空気ヨルダン-c-1.html]air jordan[/url] rsOdlAgs BelVdaOrpS [url=http://www.nikekutuja.com/nike-dunkナイキダンク-c-4.html]nike dunk[/url] yv VaqWnxVo [url=http://www.nikekutuja.com/air-maxエアマックス-c-2.html]air max 95[/url] fNqd GtiYuo Zi [url=http://www.nikekutujp.com/]nike running[/url] uNta GtnZsh BrvPjk AqwQ [url=http://www.nikekutujp.com/nike-dunkナイキダンク-c-4.html]nike dunk[/url] tbUgiJtj R [url=http://www.nikekutujp.com/nike-air-force-1ナイキエアフォース-c-3.html]nike air force 1[/url] kjRgaOrtZko [url=http://www.nikekutujp.com/air-jordan空気ヨルダン-c-1.html]air jordan[/url] CvqLgmMusRbs ZueAzf

    Reply
  • Short review illustrates the indeniable details about gucci and exactly how it might have an effect your business.

    Posted by emeseesip on 05/06/2013 07:39pm

    Just About The Most Thorough adidas Report You Ever Witnessed Or Your Cash Back [url=http://www.guccija.biz/]グッチ キーケース[/url] Wow, wonderful merchandise. You must have a look at nike straight away when it is still in store . . . [url=http://www.guccija.biz/]グッチ キーケース[/url] adidas aids all of us by simply integrating numerous one of a kind capabilities and capabilities. This is a unvaluable item for every follower of nike. [url=http://www.guccija.biz/]グッチ 財布 新作[/url] Unprejudiced post displays Five new stuff of adidas that noone is speaking about. [url=http://www.chanelja.biz/]シャネル バッグ[/url] The particular reason why nobody is debating adidas and exactly what one should accomplish right now. [url=http://www.chanelja.biz/]シャネル 長財布[/url] Contemporary questions about adidas have been answered and in addition the reasons why you should really read each message within this story. [url=http://www.chanelja.biz/]chanel バッグ[/url] An overview of nike which you can really benefit from starting up today.[url=http://www.nikeja.biz/]nike[/url] Easiest way to fully understand all that there is to find surrounding nike in Six basic steps.

    Reply
  • Isabel Marant Sneakers

    Posted by Hauddessy on 03/28/2013 11:16am

    [url=http://future-select.co.uk/fckeditor/isabelmarantsneakers.aspx]isabel marant boot sale[/url] 07 qiu dong make an appearance,,, like mashups, low-key, can concern! Isabel Marant is changed era designers in France, a occasional won a fellow of the international forge have attention. After graduating from fashion school in Paris Studio Bercot, Isabel Marant Yorke and Cole in his character as a assistant to follow. Spring/summer 2008 fashion prove in Paris - the Isabel Marant [Isabel Marant is ardent! Star display wear increased in sneakers tide lover missing concourse "mixing in the" necessary Neutral look at star street pop, nothing but certain, Isabel Marant sneakers increased works in Europe and the United States is a official spark off! Headliner, acclaimed copy wearing! Via fashion label Isabel ma LAN (Isabel Marant) to manipulate the progress of the contemporary cyclone, with hanker skirts, pants, leather pants, etc. Different particular with Isabel ma LAN (Isabel Marant), the craze sneaker row quick demonstrations, recover sports sandals teeming rocks in inspiration. Isabel ma LAN (Isabel Marant) open for good occasionally pushed on this good-natured of shoes is in dernier cri abroad, snapping up, at present in many unfamiliar shopping website cause been sold out. Miranda Kerr, louring leather pants with red [url=http://gateway.recruitment-websites.co.uk/fckeditor/isabelmarant.aspx]isabel marant sneakers[/url], reasonably of the color and style. Sulky and silver alliance colors, Isabel Marant tie-in and stringent jeans, locomotive leather, good-looking Blacklist and off-white double colors Isabel Marant jeans copy and the strong main part Isabel Marant Black even with bedeck + frog mirror, is not a indelicate examination Kate potts voss, Isabel Marant sneaker together with the heap green chiffon dresses to wear, wager is a mashup Dense cream + hand-knitted sweater fastens with color Isabel Marant Isabel Marant sneaker,Cambridge carton fluorescent color highlight is the whole body Lovers outdoors of the passage, Isabel Marant makes mother wit at wish Isabel Marant Website is efforts to gift a pass now. Isabel Marant shoes Comely mature color Isabel Marant sneaker Lightning blue and pink are quite let a child enchanted. The multicolor allocation plus ultra

    Reply
  • Inno scipt or pascal code

    Posted by Arun on 12/04/2012 01:50am

    Required pascal code to delete a folder from C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\MyApp

    Reply
  • environments

    Posted by bill4219 on 07/03/2012 11:41am

    I stumbled upon this after, like others, going nuts after setting an ENV VAR, seeing it with SET, but not getting my app to detect it properly. I found reference this past week to four 'environments' that ENV VARs use: USER, SYSTEM, PROCESS, and VOLATILE. I don't have it handy, but there is a vbscript to show the differences in how the 4 environments interpret something like TEMP=. In my case, until SYSTEM and PROCESS saw my ENV VAR SecondPartn = E:\, just the USER environment did and my script failed to detect the value of SecondPartn properly. What I was doing was reading the value of SecondPartn then Merging the corresponding .reg file into the registry. Sometimes it would work, most of the time it would not. Your explanation that a broadcast had to be made to Windows is probably what happened when sometimes the script DID work. It was quite aggravating.

    Reply
  • could not make it run from within VBA

    Posted by valboy on 05/23/2006 05:31pm

    I am writing in support of your statement that "This is mainly due to the fact that a process (SetEnv) cannot change the environment of its parent (The Command Prompt, or in my case, the VB app). However, any new DOS/Command Prompts that you open will show the new variable/value." I struggled with this issue for several days last year and could not get my VBA application (Windows XP Pro) to recognize the new environmental variable even after I executed WM_SETTINGCHANGE from within the app. But, indeed, the variable showed properly changed in My Computer/System properties/Advanced. So my workaround was to check for the environmental variable, notify the user about the situation, exit from my VB app and let the user restart the app. Very ugly and unprofessional! Unfortunately, the host VBA program could not be run in a batch file with input parameters (of course, in theory it can, but not for this particular workflow).

    • re: could not make it run from within VBA

      Posted by Darka on 05/24/2006 03:23am

      Hi valboy,
      
      It's an irritating problem I know, it took me a few days before I realised there is no easy way to do it. 
      I think it is possible by modifying the parent process directly, but it would be a massive hack
       so I decided it wasn't that important.
      
      regards,
      Darka

      Reply
    Reply
  • Bug with large values

    Posted by seligman on 05/19/2006 07:44pm

    There is a bug with values that exceed MAX_PATH. If you use -a with the "%" option to add to a variable that has an existing value longer than MAX_PATH characters, it will silently blow away the existing value with whatever was passed in with -a. I managed to destroy my %PATH% doing this :) You need to modify main.cpp:130 (" TCHAR szRegkey[_MAX_PATH] = {'\0'};") so that it doesn't use a fixed length array, but rather determines the length of the array from the registry directly.

    Reply
  • Broadcasting WM_SETTINGCHANGE

    Posted by fgorseth on 03/24/2006 05:06am

    I have added an environment variable by writing to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key. How can I broadcast WM_SETTINGCHANGE without logoff/reboot? Can I just run the SetEnv application without any parameters?

    Reply
  • spelling error

    Posted by zephyrer on 11/17/2005 06:57pm

    The Microsoft's tool is SetX, not SetEx.

    • SetX

      Posted by Darka on 11/18/2005 03:05am

      Hi zephyer, You're right of course, I shall amend the article at the weekend. Thanks.

      Reply
    Reply
  • xfc::OSVersion::IsWinME() const;

    Posted by frankd on 11/15/2005 07:09am

    fkt. returns false on ME. change: obVerInfo_.dwPlatformId == VER_PLATFORM_WIN32_NT to: obVerInfo_.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS

    • xfc::OSVersion::IsWinME() const;

      Posted by Darka on 11/15/2005 07:53am

      Thanks frankd, I didn't have a copy of ME available to test, thanks for spotting it. I will update the article a little later on. regards,

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

  • Application and data integration doesn't have to be slow and expensive. Learn how cloud-based integration platforms dramatically speed results and lower costs in this white paper by Bloor Research.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds