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?
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:
The path specified by the TMP environment variable.
The path specified by the TEMP environment variable.
The path specified by the USERPROFILE environment variable.
The Windows directory.
Thanks to Joe Angley for sharing the technique.