Just a note on this topic as I just recently needed to set up some Env. variables via MAXScript for certain in-house tools to work correctly and I bumped into a weird behavior of the .NET classes I used. So, for anyone out there with a similar task at hand, read on to save some time figuring it out.
Basically, all you need in order to get or set environment variables via .NET are two classes:
- “System.Environment”
- “System.EnvironmentVariableTarget”
Then, you simply need to call a method on the “System.Environment” class, called, simply, SetEnvironmentVariable() or GetEnvironmentVariable().
The “System.EnvironmentVariableTarget” class is used to invoke an Enum of:
- Process – this Enum will get/set the Env. variable for the actual, live, process. The Env. var. will basically die with the process as well.
- Machine – this one asks for the System Env. variables available to all users and processes
- User – this one, obviously, only applies to the given user
So, my initial approach was as usual, calling the methods this way:
sysEnv = dotNetClass "System.Environment"
envTarget = dotNetClass "System.EnvironmentVariableTarget"
sysEnv.SetEnvironmentVariable("MyVariable", @"MyValue", envTarget.Machine)
However, this threw an error:
-- Syntax error: at ),, expected
-- In line: sysEnv.SetEnvironmentVariable("MyVar", @
In such a case, I recommend using the showMethods() method for investigating .NET methods in MAXScript. This partially reveals syntax as well as actual methods available:
showMethods(dotNetClass "System.Environment")
.[static]<System.Boolean>Equals <System.Object>objA <System.Object>objB
.[static]Exit <System.Int32>exitCode
.[static]<System.String>ExpandEnvironmentVariables <System.String>name
.[static]FailFast <System.String>message
.[static]<System.String[]>GetCommandLineArgs()
.[static]<System.String>GetEnvironmentVariable <System.String>variable
.[static]<System.String>GetEnvironmentVariable
<System.String>variable <System.EnvironmentVariableTarget>target
.[static]<System.Collections.IDictionary>GetEnvironmentVariables()
.[static]<System.Collections.IDictionary>GetEnvironmentVariables
<System.EnvironmentVariableTarget>target
.[static]<System.String>GetFolderPath <System.Environment+SpecialFolder>folder
.[static]<System.String[]>GetLogicalDrives()
.[static]<System.Boolean>ReferenceEquals <System.Object>objA <System.Object>objB
.[static]SetEnvironmentVariable <System.String>variable <System.String>value
.[static]SetEnvironmentVariable <System.String>variable
<System.String>value <System.EnvironmentVariableTarget>target
So, after doing this, the correct syntax is:
sysEnv = dotNetClass "System.Environment"
envTarget = dotNetClass "System.EnvironmentVariableTarget"
sysEnv.SetEnvironmentVariable "MyVariable" @"MyValue" envTarget.Machine
Hope this helps anyone with similar issues.