What's the environment variable for the path to the desktop?
Asked Answered
S

20

72

I'm writing a Windows batch file and want to copy something to the desktop. I think I can use this:

%UserProfile%\Desktop\

However, I'm thinking, that's probably only going to work on an English OS. Is there a way I can do this in a batch file that will work on any internationalized version?

UPDATE

I tried the following batch file:

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop
FOR /F "usebackq tokens=3 skip=4" %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i
FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%

And got this output:

S:\>REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
    Desktop    REG_EXPAND_SZ    %USERPROFILE%\Desktop


S:\>FOR /F "usebackq tokens=3 skip=4" %i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folder
s" /v Desktop`) DO SET DESKTOPDIR=%i

S:\>FOR /F "usebackq delims=" %i in (`ECHO ECHO is on.`) DO SET DESKTOPDIR=%i

S:\>SET DESKTOPDIR=ECHO is on.

S:\>ECHO ECHO is on.
ECHO is on.
Strawflower answered 4/1, 2010 at 16:40 Comment(3)
@Scott Langham: Maybe Powershell (or VB script) will help youHeisser
The problem is the skip=4 option. This tells the FOR command how many header lines to skip before processing data. On XP there are 4 lines, but on my Windows 7 system - and on your system - there's only 1. So change skip=4 to skip=1 and that should work. Also, you only need the two FOR commands in your script. The first call to REG is unnecessary.Deficiency
Did you test it? As far as I know all Windows 7 and beyond uses the same path for desktop folder. It's only visually converted to the current language of the system. My system is not en-US and %UserProfile%\Desktop\ works perfectly.Gaygaya
T
21

I found that the best solution is to use a vbscript together with the batch file.

Here is the batch file:

@ECHO OFF
FOR /F "usebackq delims=" %%i in (`cscript findDesktop.vbs`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%

Here is findDesktop.vbs file:

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
wscript.echo(strDesktop)

There may be other solutions but I personally find this one less hackish.

I tested this on an English PC and also a French PC - it seems to work (Windows XP).

Trigeminal answered 4/1, 2010 at 16:40 Comment(0)
H
68

To be safe, you should use the proper APIs in Powershell (or VBScript)
Using PowerShell:

[Environment]::GetFolderPath("Desktop")

Copy something using Powershell:

Copy-Item $home\*.txt ([Environment]::GetFolderPath("Desktop"))

Here is a VBScript-example to get the desktop path:

dim WSHShell, desktop, pathstring, objFSO
set objFSO=CreateObject("Scripting.FileSystemObject")
Set WSHshell = CreateObject("WScript.Shell")
desktop = WSHShell.SpecialFolders("Desktop")
pathstring = objFSO.GetAbsolutePathName(desktop)
WScript.Echo pathstring
Heisser answered 4/1, 2010 at 17:8 Comment(2)
+1 for using the proper APIs for this. The registry shouldn't be used. (Anyone not getting this: Read Raymond Chen's blog. Yes, completely.) :-)Garfish
@Heisser Does your code take into account roaming profiles? (..."because we had forgotten to take into account a feature of Windows NT called roaming user profiles, where your user profile can move around from place to place)"....Lipsey
T
21

I found that the best solution is to use a vbscript together with the batch file.

Here is the batch file:

@ECHO OFF
FOR /F "usebackq delims=" %%i in (`cscript findDesktop.vbs`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%

Here is findDesktop.vbs file:

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
wscript.echo(strDesktop)

There may be other solutions but I personally find this one less hackish.

I tested this on an English PC and also a French PC - it seems to work (Windows XP).

Trigeminal answered 4/1, 2010 at 16:40 Comment(0)
O
17

EDIT: Use the accepted answer, this will not work if the default location isn't being used, for example: The user moved the desktop to another drive like D:\Desktop


At least on Windows XP, Vista and 7 you can use the "%UserProfile%\Desktop" safely.

Windows XP en-US it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows XP pt-BR it will expand to "C:\Documents and Settings\YourName\Desktop"
Windows 7 en-US it will expand to "C:\Users\YourName\Desktop"
Windows 7 pt-BR it will expand to "C:\Usuarios\YourName\Desktop"

On XP you can't use this to others folders exept for Desktop My documents turning to Meus Documentos and Local Settings to Configuracoes locais Personaly I thinks this is a bad thing when projecting a OS.

Ocampo answered 29/10, 2012 at 17:40 Comment(7)
It will not work for a Swedish version since it's not called Desktop in Swedish but Skrivbord. Hence, %UserProfile%\Skrivbord is the proper use for a Swedish version, and %UserProfile%\Desktop is invalid.Cumbrance
I moved my desktop to E:\Desktop. This will not work then. I'm running Windows 8.1, but I'm fairly sure you could do this on Windows 7 as well. Please don't do this as this is the most common cause of a lost icon.Zimmermann
Tis will not work if you have moved your desktop, as I have. If you have a solid state C: drive it is common practice to move your desktop onto another drive so the SSD does not get hammered with lots of writes.Larondalarosa
@Qben, the English terms will always use regardless of language. %UserProfile%\Desktop will go to %UserProfile%\Skrivbord.Kayleigh
I have located my Desktop folder at E:\Users\YourName\Desktop, but if you use %UserProfile%\Desktop you will reach C:\Users\YourName\Desktop, of which is empty.Kayleigh
Localized names are all aliases that point toDesktop (we use this safely here in Japan, Thailand, Israel and the US). The difference is whether %UserProfile% points to the user's actual profile base dir. I'm not a Windows dev, but from cross-platform dev what I've found is the profile dir is for settings, but the HOME dir is for the user's own files, so Desktop/Downloads/Pictures/etc. IIRC %HOMEDRIVE%%HOMEPATH%\Desktop is the safest way.Reliant
I'm surprised this isn't marked as the chosen answer, since this is the best answer so far imo. However @Reliant you probably should make your own answer with the solution you provided.Coleridge
F
15

KB's answer to use [Environment]::GetFolderPath("Desktop") is obviously the official Windows API for doing this.

However, if you're working interactively at the prompt, or just want something that works on your machine, the tilda (~) character refers to the current user's home folder. So ~/desktop is the user's desktop folder.

Fencesitter answered 18/4, 2010 at 20:4 Comment(3)
This is right. +1 And I beieve the desktop will always be "desktop"Heisser
You cannot assume ~/desktop works, because it can be redirected for roaming profiles. I am in that situation ;)Banner
I liked this on for my profile. Set-Location $([Environment]::GetFolderPath("Desktop")) is just what I was looking for.Anglofrench
D
9

Not only would that not work for an International version of Windows, it would fail if the user had edited the Registry to make their Desktop folder reside somewhere else. You can query the Registry for the file location using the REG command:

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop

To get this into a variable use something like this:

FOR /F "usebackq tokens=3 skip=4" %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i
FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i
ECHO %DESKTOPDIR%
Deficiency answered 4/1, 2010 at 16:45 Comment(4)
For me, on Windows 7, that returns Desktop REG_EXPAND_SZ %USERPROFILE%\Desktop which is correct but probably won't help the OP in his batch file, as he probably won't be able to parse the environment variable. Or would he just have to use it and it would parse itself?Cowage
Have added some code to parse the output of REG.EXE to the answer.Deficiency
Thanks for the tip Dave. I'm not quite there yet though - think I'm missing something. I've updated the question to show where I've got to. If you've got any more advice, it would be appreciated.Strawflower
Keep in mind that querying this from the registry is discouraged. Kb's VBScript solution is therefore the one that should be used to ensure that this works.Garfish
E
4

you could also open a DOS command prompt and execute the set command.

This will give you an idea what environment variables are available on your system.

E.g. - since you where specifically asking for a non-english Windows - heres is an example of my own German Edition (Window7-64bit) :

set > env.txt
type env.txt

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\SOF\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=VMSOF
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\SOF
LOCALAPPDATA=C:\Users\SOF\AppData\Local
LOGONSERVER=\\VMSOF
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\CMake 2.8\bin;C:\Program Files (x86)\emacs-22.3\bin;C:\Program Files (x86)\GnuWin32\bin;
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 15 Model 67 Stepping 3, AuthenticAMD
PROCESSOR_LEVEL=15
PROCESSOR_REVISION=4303
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\SOF\AppData\Local\Temp
TMP=C:\Users\SOF\AppData\Local\Temp
USERDOMAIN=VMSOF
USERNAME=SOF
USERPROFILE=C:\Users\SOF
VBOX_INSTALL_PATH=C:\Program Files\Sun\VirtualBox\
VS90COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
windir=C:\Windows

Ehtelehud answered 4/1, 2010 at 17:43 Comment(4)
Windows 7 is pretty boring, since Microsoft introduced filesystem virtualization in Windows Vista precisely to avoid problems like the one the OP is facing. IOW: Every language version of Windows 7 will have the desktop in C:\Users\%USERNAME%\Desktop even though if you actually open up Explorer it will pretend to live in C:\Benutzer (for a German system).Fairway
Off-Topic: How can you have that account name and not have a picture associated with the account? :-)Fairway
Jörg: That's only halfway correct. You can easily move the Desktop folder somewhere else. This doesn't leave a junction behind to point to the new place. Also the user's profiles doesn't need to be under C:\Users. It can be anywhere; again, no junction to point there. Those are just new defaults for paths as well as some junction points to keep programs with hard-coded legacy paths happy. Well, and to not use localized names in the file system which really makes no sense in a MUI environment.Garfish
Vokuhila: I seriously wonder where you found a DOS prompt on a 64-bit Windows :-). cmd.exe is not DOS.Garfish
V
3

in windows 7 this returns the desktop path:

FOR /F "usebackq tokens=3 " %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i 
FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i 
ECHO %DESKTOPDIR% 
Vomitory answered 21/9, 2011 at 19:47 Comment(1)
Not if the directory has spaces in it.Lopeared
C
3

If you wish to use the

[Environment]::GetFolderPath("Desktop")

from within a cmd.exe, you may do so (thanks to MS User Marian Pascalau on this thread)

set dkey=Desktop
set dump=powershell.exe -NoLogo -NonInteractive "Write-Host $([System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::%dkey%))"
for /F %%i in ('%dump%') do set dir=%%i

echo Desktop directory is %dir%
Clippers answered 17/3, 2020 at 18:22 Comment(0)
B
2

This is not a solution but I hope it helps: This comes close except that when the KEY = %userprofile%\desktop the copy fails even though zdesktop=%userprofile%\desktop. I think because the embedded %userprofile% is not getting translated.

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop>z.out
for /f "tokens=3 skip=4" %%t in (z.out) do set zdesktop=%%t
copy myicon %zdesktop%
set zdesktop=
del z.out

So it sucessfully parses out the REG key but if the key contains an embedded %var% it doesn't get translated during the copy command.

Buzzell answered 4/1, 2010 at 17:41 Comment(0)
B
2

I had a similar problem (and VBScript or PowerShell was not an option) and the code I found in this article did not work for me. I had problems with OS versions and language versions. After some experiments I've come to this solution:

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Desktop"`) do if %%A==REG_EXPAND_SZ call :reparse set desktopdir=%%B
echo %desktopdir%
goto :EOF

:reparse
%*
goto :EOF

This code works for me in English and Polish versions of Windows 7 and Windows XP.

The :reparse subroutine allows for delayed expansion of environment variables.

Bulldoze answered 9/1, 2012 at 15:57 Comment(0)
A
2

While I realize this is a bit of an older post, I thought this might help people in a similar situation. I made a quick one line VBScript to pull info for whatever special folder you would like (no error checking though) and it works like this:

Create a file "GetShellFolder.vbs" with the following line:

WScript.Echo WScript.CreateObject("WScript.Shell").SpecialFolders(WScript.Arguments(0))

I always make sure to copy cscript.exe (32-bit version) to the same folder as the batch file I am running this from, I will assume you are doing the same (I have had situations where users have somehow removed C:\Windows\system32 from their path, or managed to get rid of cscript.exe, or it's infected or otherwise doesn't work).

Now copy the file to be copied to the same folder and create a batch file in there with the following lines:

for /f "delims=" %%i in ('^""%~dp0cscript.exe" "%~dp0GetShellFolder.vbs" "Desktop" //nologo^"') DO SET SHELLDIR=%%i
copy /y "%~dp0<file_to_copy>" "%SHELLDIR%\<file_to_copy>"

In the above code you can replace "Desktop" with any valid special folder (Favorites, StartMenu, etc. - the full official list is at https://msdn.microsoft.com/en-us/library/0ea7b5xe%28v=vs.84%29.aspx) and of course <file_to_copy> with the actual file you want placed there. This saves you from trying to access the registry (which you can't do as a limited user anyway) and should be simple enough to adapt to multiple applications.

Oh and for those that don't know the "%~dp0" is just the directory from which the script is being called. It works for UNC paths as well which makes the batch file using it extremely portable. That specifically ends in a trailing "\" though so it can look a little odd at first glance.

Aurelie answered 23/3, 2016 at 17:0 Comment(0)
C
1

@Dave Webb's answer is probably the way to go. The only other thing I can think of are the CSIDLs:

CSIDL_DESKTOPDIRECTORY

The file system directory used to physically store file objects on the desktop (which should not be confused with the desktop folder itself). A typical path is C:\Documents and Settings\username\Desktop.

I have no idea how to get hold of those from the command line, though.

Cowage answered 4/1, 2010 at 16:50 Comment(0)
S
1

Multilingual Version, tested on Japanese OS
Batch File

set getdesk=REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop
FOR /f "delims=(=" %%G IN ('%getdesk% ^|find "_SZ"') DO set desktop=%%G
set desktop1=%desktop:*USERPROFILE%\=%
cd "%userprofile%\%desktop1%"
set getdesk=
set desktop1=
set desktop=
Skeptical answered 27/3, 2013 at 3:5 Comment(0)
M
1

This should work no matter what language version of Windows it is and no matter where the folder is located. It also doesn't matter whether there are any spaces in the folder path.

FOR /F "tokens=2*" %%A IN ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop^|FIND/I "desktop"') DO SET Desktop=%%B
ECHO %Desktop%

In case of Windows 2000 (and probably NT 4.0) you need to copy reg.exe to the %windir% folder manually since it is not available there by default.

Mummer answered 27/6, 2013 at 6:27 Comment(0)
S
1

I use this code to get the User desktop and Public desktop paths from the registry, tested on Windows XP SP2 pt-PT and Windows 10 b14393 en-US, so it probably works in Vista/7/8 and other languages.

:: get user desktop and public desktop paths
for /f "tokens=* delims= " %%a in ('reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop ^|find /i "REG_"') do set "batch_userdesktop=%%a"
for /f "tokens=* delims= " %%a in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v "Common Desktop" ^|find /i "REG_"') do set "batch_publicdesktop=%%a"

:: remove everything up to and including "_SZ"
set "batch_userdesktop=%batch_userdesktop:*_sz=%"
set "batch_publicdesktop=%batch_publicdesktop:*_sz=%%

:: remove leading spaces and TABs
:loop
if "%batch_userdesktop:~0,1%"==" " set "batch_userdesktop=%batch_userdesktop:~1%" & goto loop
if "%batch_publicdesktop:~0,1%"==" " set "batch_publicdesktop=%batch_publicdesktop:~1%" & goto loop
if "%batch_userdesktop:~0,1%"=="    " set "batch_userdesktop=%batch_userdesktop:~1%" & goto loop
if "%batch_publicdesktop:~0,1%"=="  " set "batch_publicdesktop=%batch_publicdesktop:~1%" & goto loop

The last two lines include a TAB inside the " ", some text editors add spaces when you press TAB, so make sure you have an actual TAB instead of spaces.

I'm not sure the code requires setlocal enabledelayedexpansion, it's part of my SETVARS.CMD which I call from other batches to set common variables like cpu architecture, account language, windows version and service pack, path to user/public desktop, etc.

Sphene answered 11/11, 2016 at 14:4 Comment(0)
D
0

I know this is kind of an old topic, but I would use the Powershell variable

$env:UserProfile 

To use it to get to the desktop, it would be:

cd $env:UserProfile\desktop

This works both locally and remotely on windows 7. Hope this is useful as I ran across a situation where a client machine didn't have a value in $home.

Didi answered 9/11, 2014 at 18:54 Comment(2)
it wouldn't work if desktop is moved to another locationAzpurua
It will not work if one drive installed, it changes the default pathPrimrose
L
0

Quite old topic. But I want to give my 2 cents...

I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%

Also there is no dependency from powershell/vbscript/etc....

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ  set desktopdir=%%B
echo %desktopdir%

Hope it helps.

Lactam answered 17/11, 2019 at 9:21 Comment(0)
R
0

TL;DR

%HOMEDRIVE%%HOMEPATH%\Desktop seems to be the safest way.

Discussion

Assumptions about which drive a thing is on are quite fragile in Windows as it lacks a unified directory tree where mounts would map to directories internally. Therefore the %HOMEDRIVE% variable is important to reference to make sure you're on the right one (it isn't always C:\!).

Non-English locales will usually have localized names for things like "Desktop" and "Pictures" and whatnot, but fortunately they are all aliases that point to Desktop, which seems to be the underlying canonical directory name regardless of locale (we use this safely here in Japan, Thailand, Israel and the US).

The big quirk comes with determining whether %UserProfile% points to the user's actual profile base dir, or their Desktop or somewhere completely different. I'm not really a Windows dev, but what I've found is the profile dir is for settings, but the %HOMEPATH% is for the user's own files, so this points to the directory root that leads to Desktop/Downloads/Pictures/etc. This tends to make %HOMEDRIVE%%HOMEPATH%\Desktop the safest way.

Reliant answered 21/12, 2020 at 12:58 Comment(0)
L
0

These commands will print the Desktop path on cmd.exe:

powershell "[System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)"
FOR /F "tokens=2*" %i IN ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop ^| findstr "desktop"') DO echo %j
Lopeared answered 24/3, 2023 at 16:18 Comment(0)
A
0

I changed my default desktop directory to E:\denis\desktop, and now, I can't just use %profilename%\desktop in cmd, it shows me C:\Users\Denis\Desktop because it contains %SystemDrive%\Users\{username}\desktop, but I can change the dir in PowerShell
Set-Location -Path ([Environment]::GetFolderPath("Desktop"))
So, [Environment]::GetFolderPath("Desktop") around () is like a variable and you can copy something like this

Copy-Item -Path C:\123.txt -Destination ([Environment]::GetFolderPath("Desktop")+"\somedir")
Aesthete answered 10/12, 2023 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.