Page 1 of 1

Increment a variable with setx

Posted: 28 Nov 2019 16:57
by einstein1969
Hi to all,

I return on this forum after a long time and i not remember how work the dos batch...

I use a macro recorder that have a possibility ok run an external command like CMD.EXE or OTHER

I need to use a variable and I need to increment this variable.

I have probed with

Code: Select all

setx x 2

Code: Select all

cmd.exe /v:on /k "set I=!x! & set /A I+=1 & setx x !I! "
but the x variable after the increment is 2 and not 3!

Where I wrong?

einstein1969

Re: Increment a variable with setx

Posted: 28 Nov 2019 17:38
by aGerman
Processes inherit their environment from the process environment of their parent. Changing the process environment of a child process will not change the environment of its parent. Changing the parent environment of a running child process will not change the environment of its child anymore. Thus, setx has no effect to the batch process from where you called your cmd.exe /k command. Setx changes the global environment (explorer.exe) but your process doesn't see this change because once it inherited the global environment, it won't be updated anymore.

Steffen

Re: Increment a variable with setx

Posted: 28 Nov 2019 18:30
by einstein1969
but if i check the global environment with another process the variable X is not incremented. Why?
How I can increment a variable over process?

Re: Increment a variable with setx

Posted: 28 Nov 2019 18:37
by aGerman
einstein1969 wrote:
28 Nov 2019 18:30
but if i check the global environment with another process the variable X is not incremented. Why?
How did you run the other process? Did it inherit a fresh global environment from explorer.exe or did you call it from another process that was already running before you changed the variable using setx?
einstein1969 wrote:
28 Nov 2019 18:30
How I can increment a variable over process?
In general you can't. The environment is given from the parent to its child. You may want to read the variable value from the registry and then use the value to update the current process environment.

Steffen

Re: Increment a variable with setx

Posted: 29 Nov 2019 03:57
by einstein1969
Ok! Thanks.