Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please consider the set of below code. I want to set the value of an environment variable using command line. That's why i am used ShellExecute.
Function execute successfully. But it will not change the environment variable value. why?
C++
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
ShellExecute(0, _T( "open" ), _T( "cmd.exe" ), _T( "/C set ALLUSERSPROFILE=C:\Program" ), 0, SW_SHOWNORMAL);
Posted

I think this will not work the way you tried it, using set within the cmd.exe shell, the change will not be globally visible.
Try the setx.exe command, this will provide a change of the environment variable that is available to other processes.
See http://stackoverflow.com/questions/3803581/setting-a-system-environment-variable-from-a-windows-batch-file[^] for more details.

For your example this would be (the environment variable will be visible to all users on this machine):
C++
ShellExecute(0, _T( "open" ), _T( "setx.exe" ), _T( "-m ALLUSERSPROFILE C:\Program" ), 0, SW_SHOWNA);
 
Share this answer
 
v3
Comments
Programmady 9-Apr-13 4:28am    
Please explain...
Steve44 9-Apr-13 4:31am    
set only changes the environment variable for the current shell session, it can not be seen from other processes, setx makes a system wide change that is available to all processes.
Programmady 9-Apr-13 4:38am    
can you show me an example?
Steve44 9-Apr-13 4:50am    
Added the code example to the solution.
 
Share this answer
 
Comments
Jochen Arndt 9-Apr-13 5:55am    
From your link:

"_putenv and _wputenv affect only the environment that is local to the current process; you cannot use them to modify the command-level environment."

So this will only affect the environment of the calling process and other processes started by the application calling _putenv() when inheriting the environment of the parent process.

The SET shell command uses _putenv() internally which declares the behaviour from Programmady's question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900