Iris Classon
Iris Classon - In Love with Code

Stupid Question 232-233: What are environment variables, and do I set and use environment variables in Command Prompt and PowerShell?

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

If you want to save the path of an executable to a permanent variable you can do so from Command Prompt or PowerShell. Setting one in Command Prompt does not set it in PowerShell. Environment variables are values stored in an object (and can be changed) and these are stored in the registry.(Stupid Question 114: What is the “Windows Registry”?).

[caption id=“attachment_7312” align=“aligncenter” width=“695”] Variable in registry Variable in registry[/caption]

The syntax for setting one temporarily is by using
set variableName C:\mypath\myExecutable.exe
To set it permanently use
setx variableName C:\mypath\myExecutable.exe

To read the contents:
echo %variableName%

To invoke/use variable:
%variableName%

In PowerShell they are set the same way,
Setx variableName C:\mypath\myExecutable.exe

But you read it by using:
gi env:variableName

And invoke/use by:
& $env:variableName

Give it a go with the C# compiler, by using (this is the path for me on my Windows 8 computer for the csc.exe) in PowerShell:
setx csc C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe

Then compile a .cs file like so:

C:\Temp\ & $env:csc test.cs

This outputstest.exe

If you prefer clicking on buttons you can set variables in Advanced System Settings:

[caption id=“attachment_7302” align=“aligncenter” width=“695”] 'Cheating' by setting variables in Advanced System Settings ;) ‘Cheating’ by setting variables in Advanced System Settings ;)[/caption]

Comments

Leave a comment below, or by email.


Last modified on 2013-08-21

comments powered by Disqus