简体   繁体   中英

set variable to cmd.exe

Greeting earthmen,

Here is my question:

How can I create a program which sets variable to current session of cmd.exe eg

c:\> set myvar
Environment variable myvar not defined
c:\>myexe.exe
c:>set myvar
myvar=myvalue

The only similar topic that I've found is this -

How can I change Windows shell (cmd.exe) environment variables from C++?

But I didn't get a single word from this:

There is a way... Just inject your code into parent process and call SetEnvironmentVariableA inside cmd's process memory. After injecting just free the allocated memory.

While C/C++ is not my "native" language I've felt myself completely lost when I've searched google with "c++ inject code" and etc... Is there an article where I can get more info about this.

BTW now I'm using one a little bit stupid workaround.As the setting a variable to

HKEY_CURRENT_USER\\Environment

and

HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment

is comparatively easy I'm just recording similar variable to the registry:

load.temp.vars=set myvar1=myval1&set myvar2=myval2& ....

and then just call %load.temp.vars% and it will be executed as a command:

c:/>%load.temp.vars%
c:/>set myvar1
myvar1=myval1

It works fine bu it's not good enough for me :)

Live long and prosper, \\\\//_

Check out this article: Three Ways to Inject Your Code into Another Process .

Also you probably will need a handle to your parent process (to determine the target process whose environment to change). A way to get it is described here .

Just keep in mind that injection may not work, depending on user account privileges, and also that some especially paranoid antivirus solutions may frown upon it.

There are very easy way to do this without any tricks .

You should write a small program myexe.exe which produce a simple output (console output) like following:

SET myvar=Some value

then you start your program with the following steps:

myexe.exe >%TEMP%\t.cmd
call %TEMP%\t.cmd
del %TEMP%\t.cmd

Now in the current cmd.exe which started myexe.exe exist the environment variable myvar and it has the value Some value . Is it not exactly what you want?

The way is extrem simple and it works on all versions of Windows (and not only Windows). So it is my recommendation for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM