[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[news.eclipse.platform] Re: how to set system environment variables programmatically?

Hi Joneo,

The Microsoft setx.exe utility, which have from the Windows NT 4.0 resource kit, allows you to change an environment variable from a command line such that it will change the global environment settings. The version I have (1.0a 5/31/96) appears to work fine on Windows XP SP2.

Here is the setx's help string :

SETX: This program is used to set values in the environment of the machine or
currently logged on user using one of three modes. Without SETX, there is no
method for settings values directly into the master environment for Windows
NT. These are configureable only through Control Panel or through the
Registry Editor. The SET command, which is internal to the command
interpreter, sets variables only into the environment of the current window.
SETX allows you to set values for variables in either the user or computer
environment from one of three sources: Command Line Mode, Registry Mode, and
File Mode.


You can download it from :

http://download.microsoft.com/download/win2000platform/setx/1.00.0.1/nt5/en-us/setx_setup.exe

Here is my method to read Window's environment variables (wich use the SET command):

private static Properties getEnvVars() throws Throwable {
Properties envVars = new Properties();
if ( envVars != null ) {
Runtime r = Runtime.getRuntime();
if ( r != null ) {
Process p = null;
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("windows 9") > -1) {
p = r.exec("command.com /c set");
} else if ((OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 20") > -1)
|| (OS.indexOf("windows xp") > -1)) {
p = r.exec("cmd.exe /c set" );
} // no linux support !
if ( p != null ) {
BufferedReader br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
if ( br != null ) {
String line;
while ((line = br.readLine()) != null) {
int idx = line.indexOf('=');
envVars.setProperty( line.substring(0, idx), line.substring(idx + 1) );
}
return envVars;
}
}
}
}
return null;
} // end of getEnvVars()


And a method to set an environment variable (wich use the SETX command):

private static void setEnvVars( String _variable, String _value ) throws Throwable {
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
if (OS.indexOf("windows 9") > -1) {
r.exec("command.com /c setx.exe "+_variable+" "+_value);
} else if ((OS.indexOf("nt") > -1)
|| (OS.indexOf("windows 20") > -1)
|| (OS.indexOf("windows xp") > -1)) {
r.exec("cmd.exe /c setx.exe "+_variable+" "+_value);
}
// no linux support !
} // end of setEnvVars()


Of course, your code becomes not-portable...
--
Philippe