view raw
Noah Sussman Noah Sussman - 8 months ago 37
Ruby Question

Use Ruby to permanently (ie, in the registry) set environment variables?

On Windows, how can I use Ruby to permanently set an environment variable? I know I need to change the registry (through the win32ole module?) but I am a novice with regard to scripting the registry.

I understand that I can say

ENV['FOO'] = "c:\bar\baz"
to set the environment variable
for the session. However, I am instead interested in setting environment variables globally and permanently.

I did find the patheditor gem, which works great for permanently altering the Windows
. But I want to set other environment variables, for example,


There is a past question about this. The basic gist is to set the variable in the registry via Win32::Registry (like runako said). Then you can broadcast a WM_SETTINGCHANGE message to make changes to the environment. Of course you could logoff/logon in between then too, but not very usable.

Registry code:

require 'win32/registry.rb''Environment', Win32::Registry::KEY_WRITE) do |reg|
  reg['ABC'] = '123'


require 'Win32API'  

    SendMessageTimeout ='user32', 'SendMessageTimeout', 'LLLPLLP', 'L') 
    HWND_BROADCAST = 0xffff
    result = 0, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, result)

Thanks to Alexander Prokofyev for the answer.

Also see a good discussion on Windows environment variables in general, including how to set them for the entire machine vs. just the current user ( in HKEY_LOCAL_MACHINE\ SYSTEM\ CurrentControlSet\ Control\ Session Manager\ Environment)