55

In traditional cmd, we can use cd %programfiles% to switch directory which usually resolves to C:\Program Files.

In PowerShell, how can we go to a directory by a environment variable?

2 Answers 2

99

The principle is:

$Env:variablename

So you might try:

cd $Env:Programfiles

or to temporarily switch working directory to %Programfiles%\MyApp:

Push-Location -Path "$Env:Programfiles\MyApp"
#
# command execution here
#
Pop-Location

To list all environment variables you could do:

Get-ChildItem Env:

or use the convenient alias:

ls env:
2
  • If I want to go to C:\Program Files\Common Files, how should I write the command? It seem very strange that I can use cd $env:ProgramFiles"\Common Files" without + to concatenate the two strings. Can you explain?
    – Gqqnbig
    Nov 22, 2013 at 20:55
  • I found some articles explaining this: roelvanlisdonk.nl/?p=1153 jrich523.wordpress.com/2011/07/01/…
    – Gqqnbig
    Nov 23, 2013 at 23:55
14

To see all the environment variables, do this:

dir env:

To see all the ones containing "Program", do this:

dir env: | ? { $_.Value -match 'Program' }

In PowerShell 3 it is cleaner:

dir env: | ? Value -match 'Program'

The one we want is env:ProgramFiles, and we can just do this:

cd $env:ProgramFiles
2
  • 1
    Really annoying how if you enter a typo in the variable name, it silently fails with no explanation. Feb 11, 2016 at 15:54
  • It does offer tab-autocomplete though... kind of nice. It'd be better if $e-tab would autocomplete to $env: instead of jumping to the first environment variable, though... Feb 11, 2016 at 16:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.