Noah Sussman Noah Sussman - 2 months ago 13
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
FOO
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
PATH
. But I want to set other environment variables, for example,
JAVA_HOME
.

Answer

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'

Win32::Registry::HKEY_CURRENT_USER.open('Environment', Win32::Registry::KEY_WRITE) do |reg|
  reg['ABC'] = '123'
end

WM_SETTINGCHANGE code:

require 'Win32API'  

    SendMessageTimeout = Win32API.new('user32', 'SendMessageTimeout', 'LLLPLLP', 'L') 
    HWND_BROADCAST = 0xffff
    WM_SETTINGCHANGE = 0x001A
    SMTO_ABORTIFHUNG = 2
    result = 0
    SendMessageTimeout.call(HWND_BROADCAST, 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)