When using BAT, I need to access the My Documents directory. I found that no system environment variable points there, and my My Documents has been customized so it is not at the system default location %USERPROFILE%\My Documents, so I read the value of Personal under HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders from the registry and assign it to a variable for use.
This method works well on my machine, but on other machines where the My Documents location has not been customized, the value obtained from the registry is %USERPROFILE%\My Documents, and I want to expand it once more so it becomes a value without any unexpanded variables, such as C:\Documents And Settings\UserName\My Documents.
My current solution is as follows. It feels a bit verbose, and I hope to see a more concise way to achieve the same effect. Also, if there is a simpler way to get the My Documents directory, please do share it. Thanks!
@ECHO OFF
FOR /F "tokens=2*" %%I IN ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" ^| FIND /i "Personal"') DO SET "Personal=%%J"
CALL :ExpandPathMacro "%Personal%" Personal
ECHO %Personal%
PAUSE
@ECHO ON
@GOTO :EOF
:: Expand path macro, parameter 1 is the string to be expanded, parameter 2 is the return variable name
:ExpandPathMacro
SETLOCAL ENABLEDELAYEDEXPANSION
SET "EPM=%~1"
SET "EPM=!EPM:%%=?!"
SETLOCAL ENABLEEXTENSIONS & ENDLOCAL & SET "EPM=%EPM:?=!%"
ENDLOCAL & SET "%2=%EPM%"
GOTO :EOF
[ Last edited by BatMan on 2008-1-5 at 02:15 PM ]
This method works well on my machine, but on other machines where the My Documents location has not been customized, the value obtained from the registry is %USERPROFILE%\My Documents, and I want to expand it once more so it becomes a value without any unexpanded variables, such as C:\Documents And Settings\UserName\My Documents.
My current solution is as follows. It feels a bit verbose, and I hope to see a more concise way to achieve the same effect. Also, if there is a simpler way to get the My Documents directory, please do share it. Thanks!
@ECHO OFF
FOR /F "tokens=2*" %%I IN ('REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" ^| FIND /i "Personal"') DO SET "Personal=%%J"
CALL :ExpandPathMacro "%Personal%" Personal
ECHO %Personal%
PAUSE
@ECHO ON
@GOTO :EOF
:: Expand path macro, parameter 1 is the string to be expanded, parameter 2 is the return variable name
:ExpandPathMacro
SETLOCAL ENABLEDELAYEDEXPANSION
SET "EPM=%~1"
SET "EPM=!EPM:%%=?!"
SETLOCAL ENABLEEXTENSIONS & ENDLOCAL & SET "EPM=%EPM:?=!%"
ENDLOCAL & SET "%2=%EPM%"
GOTO :EOF
[ Last edited by BatMan on 2008-1-5 at 02:15 PM ]

Thanks, post #3! Learned something!