Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change to temp directory in PowerShell?

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?

like image 461
Iain Samuel McLean Elder Avatar asked May 28 '12 10:05

Iain Samuel McLean Elder


1 Answers

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.

like image 53
Iain Samuel McLean Elder Avatar answered Oct 09 '22 18:10

Iain Samuel McLean Elder