windows cmd(clink) doskey, how to copy the current directory to clipboard, prepended by "cd"?

852 Views Asked by At

It is ok to do this in the command line:

C:\Users\ken.chen>echo|set /p=cd %cd%|clip

C:\Users\ken.chen>cd C:\Users\ken.chen

C:\Users\ken.chen\nuts\notes>echo|set /p=cd %cd%|clip

C:\Users\ken.chen\nuts\notes>cd C:\Users\ken.chen\nuts\notes

but the variabe %cd% is always my home directory if I add a doskey cc to my initialization batch file:

doskey cc=echo^|set /p=cd %cd%^|clip


C:\Users\ken.chen\nuts\notes>cc

C:\Users\ken.chen\nuts\notes>cd C:\Users\ken.chen

how to fix it? or do I need to write it in a separate batch file?

2

There are 2 best solutions below

3
On BEST ANSWER

The cd variable always "contains" the same directory because it was evaluated once, when the macro was created, and at that point the home directory was current.

If you escape the % characters, however, the variable will be evaluated at every invocation of cc:

doskey cc=echo^|set /p=cd ^%cd^%^|clip

But that method of escaping the % would work only in the command line. To escape them in a batch file, use a different method:

doskey cc=echo^|set /p=cd %%cd%%^|clip
0
On

Can you not simply use the below?

echo.cd "%cd%" | clip

alternate methods-

If your path does not contain any space, you could do it with the one liner -

for /f "tokens=3" %%i in ('dir ^|findstr /i /c:"directory of"') do (echo.cd "%%i"| clip)

If it contains any space(s) -

for /f "delims=" %%i in ('dir ^| findstr /i /c:"Directory of"') do set mypath=%%i
set mypath=%mypath: Directory of =%
echo.cd "%mypath%"| clip

Cheers, G