Persistent Environment Variable creation in MAXScript

loocas | 3ds Max,dotNET,maxscript | Monday, May 27th, 2013

This is a quick note to anyone who wishes to set certain environment variables for whatever reason.

If you’ve already done this and know what the EnvironmentVariableTarget Enumeration is, you can skip this post. But to the rest of you, listen up.

If you try to set an Environment Variable in a running process, the default behavior is that the Env Var will be stored in a Process location. This is a sandboxed location available and only valid throughout the process, that created it, lifetime. When you exit the process, the Env Vars will die with it. What this means is you cannot depend on such Env Vars for future reference (i.e. when you restart your process).

This is where the EnvironmentVariableTarget Enumeration comes into play. The other two locations you can use are User and Machine. While the User location will only be available to the specific user that is logged in at the time of the Env Var retreival, the Machine location is global, meaning all users will be allowed to source such an Env Var.

So, in practice, let’s look at MAXScript’s code to do so:

To store an Environment Variable “FOO” containing “BAR” for the currently logged in user, this is what you want to write:

dnEnv = dotNetClass "System.Environment"
dnEnvTarget = (dotNetClass "System.EnvironmentVariableTarget").User

dnEnv.SetEnvironmentVariable "FOO" "BAR" dnEnvTarget


To store an Environment Variable “FOO” containing “BAR” for all the users on the machine, this is what you want to write:

dnEnv = dotNetClass "System.Environment"
dnEnvTarget = (dotNetClass "System.EnvironmentVariableTarget").Machine

dnEnv.SetEnvironmentVariable "FOO" "BAR" dnEnvTarget


And if you omit the dnEnvTarget variable completely, which is the default behavior, or if you use Process Enumeration, the Environment Variable will only be available throughout the lifetime of the running process, which is rather convenient if you only want to setup some variables temporarily (such as license paths on render slaves only during the rendering etc…)

Hope this helps.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress | Theme by Roy Tanck