9

In PowerShell I can echo the value of %TEMP% using the command $Env:TEMP. Here is the output on my machine:

PS> $Env:temp
C:\Users\IAIN~1.COR\AppData\Local\Temp

When I try to change to the directory using the cd command, I receive this error:

PS> cd $Env:temp
Set-Location : An object at the specified path C:\Users\IAIN~1.COR does not exist.
At line:1 char:3
+ cd <<<<  $Env:temp
    + CategoryInfo          : InvalidArgument: (:) [Set-Location], PSArgumentException
    + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.SetLocationCommand

I suspect that PowerShell is interpreting the 8.3 file name literally. The long file name of the directory is C:\Users\iain.CORP\AppData\Local\Temp. When I try cd C:\Users\Iain.CORP\AppData\Local\Temp, the directory changes successfully.

How can I open the path in $Env:TEMP using PowerShell? Do I have to have the long file name first?

Iain Samuel McLean Elder
  • 19,791
  • 12
  • 64
  • 80

4 Answers4

14

You don't need to access the %TEMP% environment variable directly.

.NET provides a GetTempPath method as a more general solution.

$TempDir = [System.IO.Path]::GetTempPath()
cd $TempDir

On my machine, this changes to the directory C:\Users\Iain.CORP\AppData\Local\Temp.

Remarks from the documentation:

This method checks for the existence of environment variables in the following order and uses the first path found:

  1. The path specified by the TMP environment variable.

  2. The path specified by the TEMP environment variable.

  3. The path specified by the USERPROFILE environment variable.

  4. The Windows directory.

Thanks to Joe Angley for sharing the technique.

Iain Samuel McLean Elder
  • 19,791
  • 12
  • 64
  • 80
9

Open $env:temp by first resolving its fullname like this:

cd (gi $env:temp).fullname
jon Z
  • 15,838
  • 1
  • 33
  • 35
  • Thanks, that worked for me. In the end I decided to use [the .NET method](http://stackoverflow.com/a/10783291/111424) because it is more robust than relying on one environment variable. See my answer for more details. – Iain Samuel McLean Elder May 28 '12 at 17:09
8

cd $env:temp

This worked for me.

Layke
  • 51,422
  • 11
  • 85
  • 111
JoelT
  • 89
  • 1
  • 1
  • 2
    This fails in my environment, as I demonstrated in the question. What does it return in yours? I think this method will fail in an environment in which `$Env:TEMP` returns an [8.3 File Name](http://support.microsoft.com/kb/142982) rather than the Long File Name. – Iain Samuel McLean Elder Oct 12 '12 at 14:22
-1

I want to suggest using the native .Net method to get system TEMP path GetTempPath() instead of retrieving from a local system variable like $Env:TEMP

So you can find the path with greater assurance:

cd $([System.IO.Path]::GetTempPath())

or in a little programmatically way like this:

$tmpPath = [System.IO.Path]::GetTempPath()
cd $tmpPath

enter image description here

Bobbiz
  • 43
  • 1
  • 4