How do I create a symbolic link using a batch script in windows?
Asked Answered
D

1

9

I am currently using the following script to copy all files with a certain prefix to a target directory:

for /f "delims==" %%k in ('dir "d:\Search Path\File Prefix*.*" /s /b') do copy "%%k" "d:\Target Directory\"

This works fine but I would like to instead create a symlink to the files incase of any file changes. Please can someone advise how I could do this?

Many Thanks

Dodger answered 11/3, 2014 at 10:21 Comment(1)
Here simplest and powerful .bat : puvox.software/blog/easiest-method-create-symlink-symbolicGordongordy
S
9

You utilise the mklink command:

for /f "delims==" %%k in ('dir "d:\Search Path\File Prefix*.*" /s /b') do (
mklink "d:\Target Directory\" "%%~k"
)

And that should solve your problem. mklink /? for more info.

Mona.

Syllabism answered 11/3, 2014 at 10:27 Comment(3)
Hi Mona, thank I have tried this and it look as if it should work but I am getting error "Access is Denied" (running as Domain Admin). Any ideas?Dodger
Okay. I worked it out, the above script was almost correct but returning "Access is Denied" because the link target does not reference the filename and extension the code works if it is changed to: for /f "delims==" %%k in ('dir "d:\Search Path\File Prefix*.*" /s /b') do (mklink "d:\Target Directory\%%~nxk" "%%~k")Dodger
If you don't need the link anymore use "rmdir" to delete it. Do NOT use "del" because it will remove all files from the target directory.Libreville

© 2022 - 2024 — McMap. All rights reserved.