Short answer: Use the substring syntax to strip the first two characters from the %cd%
pseudo-variable:
%cd:~2%
To remove the first backslash too:
%cd:~3%
This reliably works even with Unicode paths when the console window is set to raster fonts.
Longer answer, detailing some more options (none of which work well enough):
For arguments to the batch file you can use the special syntax %p1
, which gives you the path of the first argument given to a batch file (see this answer).
This doesn't work the same way with environment variables but there are two tricks you can employ:
Use a subroutine:
call :foo "%cd%"
...
goto :eof
:foo
set result=%~p1
goto :eof
Subroutines can have arguments, just like batch files.
Use for
:
for %%d in ("%cd%") do set mypath=%%~pd
However, both variants don't work when
- The console is set to "Raster fonts" instead of a TrueType font such as Lucida Console or Consolas.
- The current directory contains Unicode characters
- That have no representation in the current legacy codepage (for Western cultures, CJK is a good choice that doesn't fit). Remember that in this case you'll only get question marks instead of the characters.
The problem with this is that whil environment variables can hold Unicode just fine you'll get into problems once you try setting up a command line which sets them. Every option detailed above relies on output of some kind before the commands are executed. This has the problem that Unicode isn't preserved but replaced by ?
. The only exception is the substring variant at the very start of this answer which retains Unicode characters in the path even with raster fonts.