Noah Sussman - 11 months ago 48
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
.

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