Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for truename.bat

(view source code of truename.bat as plain text)

  1. @ECHO OFF
  2. :: Check Windows version and command line arguments
  3. IF NOT "%OS%"=="Windows_NT" GOTO Syntax
  4. IF      "%~1"==""           GOTO Syntax
  5. IF NOT  "%~2"==""           GOTO Syntax
  6. IF NOT EXIST "%~dp1"        GOTO Syntax
  7.  
  8. :: Do not test UNC paths
  9. ECHO "%~f1" | FINDSTR.EXE /R /B /I /C:"""\\\\[A-Z]"
  10. IF NOT ERRORLEVEL 1 GOTO:EOF
  11.  
  12. SETLOCAL ENABLEDELAYEDEXPANSION
  13.  
  14. SET MyPath="%~f1"
  15. SET MyDrive="%~d1"
  16.  
  17. :AllOverAgain
  18. SET TrueName=%MyPath%
  19.  
  20. :: Find out if the drive is a mapped network drive,
  21. :: and if so translate the drive letter to its UNC path
  22. FOR /F "tokens=1* delims=\" %%A IN ('NET.EXE USE %~d1 2^>NUL ^| FIND.EXE "\\"') DO (
  23. 	REM Nested FOR loop removes leading spaces
  24. 	FOR /F "tokens=* delims= " %%C IN ("%%~B") DO (SET TrueName="\\%%~C%~pnx1")
  25. 	REM UNC path will not be tested any further
  26. 	ECHO !TrueName!
  27. 	ENDLOCAL
  28. 	GOTO:EOF
  29. )
  30.  
  31. :: Check if the drive is SUBSTituted, and if so find out its true path
  32. :: Delims is a greater than, followed by a tab and a space
  33. FOR /F "tokens=2* delims=>	 " %%A IN ('SUBST.EXE ^| FINDSTR.EXE /B "%~d1\: =>"') DO (
  34. 	SET Subst=%%B
  35. 	IF "!Subst:~0,4!"=="UNC\" SET Subst=\!Subst:~3!
  36. 	SET TrueName="!Subst!%~pnx1"
  37. 	SET MyPath=%TrueName%
  38. 	GOTO AllOverAgain
  39. )
  40.  
  41. :: Check for file/directory junctions, starting at the specified folder, then its parent, etc.
  42. SET TestDir=%TrueName%
  43. :Iterate
  44. FOR /F "tokens=*" %%A IN (%TestDir%) DO (SET TestSub=" %%~nxA [")
  45. FOR /F "tokens=*" %%A IN ("%TestDir:~1,-1%.\..") DO (SET TestDir="%%~fA")
  46. FOR /F "tokens=2 delims=[]" %%A IN ('DIR /ADL !TestDir! 2^>NUL ^| FIND.EXE /I %TestSub%') DO (
  47. 	SET TrueName=!TrueName:%TestDir:~1,-1%\=%%~dpA!
  48. 	SET MyPath=!TrueName!
  49. 	GOTO AllOverAgain
  50. )
  51. FOR %%A IN (%TestDir%) DO (
  52. 	IF NOT "%%~pA"=="\" (
  53. 		GOTO Iterate
  54. 	)
  55. )
  56.  
  57. ECHO.%TrueName%
  58.  
  59. :End
  60. ENDLOCAL
  61. GOTO:EOF
  62.  
  63.  
  64. :Syntax
  65. ECHO.
  66. ECHO TrueName,  Version 3.00 for Windows NT 4 and later
  67. ECHO Displays the true path of a file or directory, like COMMAND.COM's internal
  68. ECHO TRUENAME command; handles SUBSTituted drives as well as mapped network
  69. ECHO drives and directory junctions, and even some combinations.
  70. ECHO.
  71. ECHO Usage:  TRUENAME  "d:"
  72. ECHO    or:  TRUENAME  "d:\path"
  73. ECHO    or:  TRUENAME  "d:\path\filename.ext"
  74. ECHO.
  75. ECHO As always, enclosing paths and file names in doublequotes is recommended.
  76. ECHO.
  77. ECHO Written by Rob van der Woude
  78. ECHO http://www.robvanderwoude.com
  79.  

page last uploaded: 2017-07-06, 12:37