0

This is a very quick question because I'm nervous to break my batch file/java environment or make my laptop explode.

I used to used to execute a .bat file from cmd.exe to set my environment to java which worked and that but now I've upgraded to Windows Powershell.

I've created a Powershell .ps version of the .bat file to set my java environment path as bellow.

echo "setting environment to Java"
$env:path="$env:Path;C:\Program Files\Java\jdk1.8.0\bin"

This works fine but I was wondering if it's possible to include a second line to add the JDBC to the classpath as well

echo "setting environment to Java"
$env:path="$env:Path;C:\Program Files\Java\jdk1.8.0\bin"
$env:path="$env:Path;C:\Program Files (x86)\MySQL\MySQL Connector J"

just wanted a second opinion to avoid breaking everything (which I have done before).

Will this end up setting my environment and adding an additional classpath or will it just overwrite the environment with just the MySQL Connector path.

1 Answer 1

3

What you have should be fine. To be consistent with everything else, end your paths with a backslash. Also, if you think your script may get called multiple times and want to always be sure duplicates get cleaned out of the path, you could try making an AddToPath function with something like this:

function AddToPath ([string]$path)
{
  $delimeter = ';'
  $path = Get-Item -path $path
  $newEnvPath = $env:path + ";" + $path
  $newEnvPath = ($newEnvPath -split $delimeter | select -Unique) -join $delimeter
  $env:path = $newEnvPath
}

Then, you could AddToPath -path "C:\Program Files\Java\jdk1.8.0\bin\", etc.

Sign up to request clarification or add additional context in comments.

6 Comments

Easier than that... "C:\path\java\blah","C:\path\otherjava" | Where{$env:path -notmatch [regex]::escape($_)} | ForEach{$env:path+=";$_"} or in your function If($env:path -notmatch $path){$env:path += ";$path"}
That trusts that nothing else has duplicated itself already, but I like it. That change is going in my personal scripts. Thanks, @TheMad !
True enough, but for adding paths it's ideal. Yours might be better for cleaning up the $env:path variable. Oh, I just noticed, I didn't [regex]::escape($path) in the second code snippet I put in my first comment. You may want to fix that if you incorporate that into your scripts.
Fell asleep at my computer again =D
I've just found the reason it wasn't working in the first place, it's falling over at the Program Files (x86). I think the brackets are interfering with the path. Is there a way to escape the brackets?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.