Can I set an environment variable for an application using a shortcut in Windows?

Solution 1:

As explained here: http://www.labs64.com/blog/2012/06/set-environment-variables-in-windows-shortcut/ you can do it without a bat file too.

Set Target to e.g.:

C:\Windows\System32\cmd.exe /c "SET path=%path%&& START /D ^"C:\Program Files (x86)\Notepad++^" notepad++.exe"

To avoid see the command prompt for a split second before it close again, you should set

Run: Minimized 

on the Shortcut tab

(Tested on Windows 7, Windows 10)

Solution 2:

Let the shortcut execute a batch file (.cmd), that

  • Sets the environment variable
  • execute the app
  • You use "START" to execute the app, this will start the app in another process, but it will copy the environment. You do not wait for the app to finish.
  • Now you can exit the batch file.

Should look like this:

@echo off
set path=%path%;C:\My Folder
start "Window Title" "Path to my exe"

Solution 3:

Linking directly to a batch file spawns an annoying console that you probably want to avoid. Here's a work-around. The simpler solution is to use the "Start Minimized" option in your link, but on Windows 7 you'll see a momentary console light up your task bar.

start.bat:

@echo off
IF "%1" == "" GOTO Error
IF "%2" == "" GOTO Error
IF NOT EXIST %2 GOTO Error
SET PATH=%1;%PATH%
start %2
GOTO End

:Error
echo Problem!
pause

:End

shortcut target:

MyPath = "C:\MyApp"
Set shell = WScript.CreateObject("WScript.Shell")
cmd = "start.bat " & MyPath & " MyApp.exe"
shell.Run cmd, 0, false
Set env = Nothing
Set shell = Nothing

Solution 4:

You can do this with PowerShell easily. PowerShell exposes environment variables using the $env: prefix. For example, I wanted to launch TeamSQL with custom JAVA_HOME and PATH environment variables, so I could connect to a PostgreSQL database. TeamSQL depends on JDK / OpenJDK for this purpose.

First, I downloaded pre-built OpenJDK and extracted the ZIP archive with 7-Zip.

Next, in PowerShell, I ran the following:

$env:JAVA_HOME='C:\Users\TrevorSullivan\Downloads\openjdk\jdk-11.0.2\'
$env:PATH += ';%JAVA_HOME%\bin'

# Launch TeamSQL
& C:\Users\TrevorSullivan\AppData\Local\Programs\TeamSQL\TeamSQL.exe

Store that PowerShell code in a .ps1 file, and you can run it with PowerShell. Because child processes inherit the environment variables from the PowerShell session, your program is good to go.