Monday, June 30, 2014

How To Adjust Environment Variables

How To Adjust Environment Variables
by Charlie Marlin

This post is similar to a post by Joey Rogers on Friday, February 11, 2011.  It has slight differences in language and syntax, but I thought I should share it just the same.  Windows 7 installations should also see the “Fly in Ointment” note at the end.

Sometimes you need to change a system variable for a section of code.  Where I work, we have some Oracle databases on the 11g version and some on version 8.  They reside on different servers.  When we want to use one, it often works fine.  If we need to use the other, we have to edit the PATH variable on our machines to move the reference to the unwanted Oracle version further down the path than the desired version.  I have lived with this limitation for years, hoping the old database would get upgraded, but last week I was placed in a situation of telling a user who does not have admin credentials that will allow him to edit the environment variables to use one laptop for one thing and another laptop for the other.  Embarrassing.  So I groped around and found this, tested it, delivered it to the user, and to my astonishment it worked.

(Let’s name the old Oracle 8 server “Aristophanes” and the more modern Oracle 11g server “Moliere”. In the code before I need “C:\ORANT\BIN:” not to come before the home for Oracle 11g I place this code:)

' First, we need to change the PATH environment variable in order to reach Moliere...
Dim oraclePathAristophanes As String = Environment.GetEnvironmentVariable("path")
Dim oraclePathMoliere As String = oraclePathAristophanes

oraclePathMoliere = oraclePathAristophanes.Replace("C:\ORANT\BIN;", "")
'MessageBox.Show("Oracle PATH edited: " & vbCrLf & oraclePathMoliere)

Environment.SetEnvironmentVariable("path", oraclePathMoliere)
' restore oraclePathAristophanes further down once we are done with Moliere...
'MessageBox.Show("Oracle PATH set: " & vbCrLf & Environment.GetEnvironmentVariable("path"))

(then later in the sub I restore the old path variable)

' restore oraclePathAristophanes once we are done with Moliere...
Environment.SetEnvironmentVariable("path", oraclePathAristophanes)

'MessageBox.Show("Oracle PATH restored: " & vbCrLf & Environment.GetEnvironmentVariable("path"))



Fly in Ointment

This approach fails on Windows 7 for non-admin users, but the following article lets you step over that obstacle:  http://williamfaulkner.co.uk/2009/04/vbnet-run-as-administrator-impersonate-a-user-2008/

No comments: