Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an environment variable in Windows PowerShell

Tags:

powershell

cmd

I am having trouble replicating this command from CMD set APPDATA=D:\.

The best equivalent I have is Set-Variable -Name $env:APPDATA -Value D:\. This does not work!

The full script is:

set APPDATA=D:\
start java -jar D:\.minecraft\minecraft.jar

This sets it so Java looks in D:\ for .minecraft instead of APPDATA.

The full PowerShell version (which doesn't work right) is:

& Set-Variable -Name $env:APPDATA -Value D:\
& 'C:\Program Files\Java\jre1.8.0_66\bin\java.exe' -jar D:\.minecraft\Minecraft.jar

It still looks at the read-only version of $env:APPDATA. I don't see why it can't be changed in the running environment for the shell's session, like cmd and most *nix shells!

I'm sure there are more uses for this than just running Minecraft. :P

like image 543
Whitequill Riclo Avatar asked Jan 01 '16 19:01

Whitequill Riclo


1 Answers

When you use Set-Variable the -Name argument should NOT have the dollar sign ($).

# WRONG: Set's the variable using the name stored in ENV:APPDATA
Set-Variable -Name $env:APPDATA -Value D:\

Also, Set-Variable doesn't appear to work as expected with environment variables. I'm assuming this is because Set-Variable is specifically designed to work with Variable: variable provider, rather than the env: environment provider. (I verified this locally, using Set-Variable -Name ENV:AppData -Value "foo" created a variable called 'ENV:AppData' in the Variable: provider.)

Alternative 1 (simple format):

$ENV:AppData="D:\"
& 'C:\Program Files\Java\jre1.8.0_66\bin\java.exe' -jar D:\.minecraft\Minecraft.jar

Alternative 2 (using C# API):

[Environment]::SetEnvironmentVariable("APPDATA", "D:\")
like image 175
Eris Avatar answered Sep 20 '22 19:09

Eris