Updating the Path environment variable from nAnt scripts

I couldn't seem to find a way to update the Path environment variable using the 'stable' build of nAnt.  Setting sys.env.Path doesn't update the system environment variable, though the ${sys.env.Path} property will appear to be updated.  This can be somewhat confusing.

So, I've written a target, instead.  This "updatepath" target will update the path for the length of the nAnt build.  Set the "build.appendpath" property before calling this target, and be certain to call the <sysinfo/> task as well. 

A similar method could be used for any environment variable:

 

<target name="updatepath">
   
<script language="C#"> 
   
<code><![CDATA[

   public static void ScriptMain
(Project project)
   
{
      string currentPath = project.Properties[
"sys.env.Path"];
      
      // make certain that there is a trailing semicolon
      if
(!(currentPath.EndsWith(";"))) currentPath += ";";

      string updatedPath = currentPath
+ project.Properties["build.appendpath"];
      
SetEnvironmentVariable("Path", updatedPath);
   }

   [ System.Runtime.InteropServices.DllImport( "kernel32") ]
   public static extern bool SetEnvironmentVariable( string EnvironmentVariable, string EnvironmentValue );

      ]]></code>
   
</script>
</target>

3 Comments

  • Is there no other way of achieving this, although your solution is nice, it seems odd that NAnt cannot cope with modifying environments??

  • If I could have found an easier way to do this in nAnt, I would have used it. If there is an easier way in 0.84, I'd like to know, myself.

  • So, for some reason, that's not working for me on 0.84.



    Here's a simplified version that should be pretty straightforward:



    &lt;target name=&quot;updatepath&quot;&gt;

    &lt;property name=&quot;build.appendpath&quot; value=&quot;test&quot;/&gt;

    &lt;script language=&quot;C#&quot;&gt;

    &lt;code&gt;&lt;![CDATA[



    public static void ScriptMain(Project project)

    {

    string x = project.Properties[&quot;sys.env.x&quot;];

    System.Console.WriteLine(&quot;x was: &quot; + x);

    System.Console.WriteLine(&quot;Changing to: &quot; + project.Properties[&quot;build.appendpath&quot;]);

    SetEnvironmentVariable(&quot;x&quot;, project.Properties[&quot;build.appendpath&quot;]);

    System.Console.WriteLine(&quot;x is: &quot; + x);

    }





    [ System.Runtime.InteropServices.DllImport( &quot;kernel32&quot;) ]

    public static extern bool SetEnvironmentVariable( string EnvironmentVariable, string EnvironmentValue );





    ]]&gt;&lt;/code&gt;

    &lt;/script&gt;

    &lt;echo message=&quot;x=${sys.env.x}&quot;/&gt;

    &lt;/target&gt;



    When you run this, the output is:

    updatepath:



    x was: 0

    Changing to: test

    x is: 0

    [echo] x=0



    BUILD SUCCEEDED



    What'd I do wrong?

Comments have been disabled for this content.