Question

Which is the best way to archieve this? I was thinking on a batch script that takes a source folder and a destination folder as inputs, and then iterates recursively over the source folder and for each file creates a hard link to that file (with the same name) in the destination folder.

hardlink.bat "src dir" "dst dir"

results:
->src dir\file1 <==> dst dir\file1
->src dir\subdir\file2 <==> dst dir\subdir\file2

I tried doing this with a for loop, but my experience with batch scripting is limited, and I don't know how to split the source folder name to recreate the same directory structure in the destination folder. Any hints would be greatly appreciated!

P.D: The solution could use any scripting language. I currently have python 2.7.3 installed

Was it helpful?

Solution

I like the free Link Shell Extension which gives you GUI tools to create hardlinks and is integrated right into Explorer.

If you want to do it from a script, you can execute Windows' fsutil utility. Another very good free alternative is the junction utility from SysInternals..

Either can be invoked from a batch script. Likewise, to execute one or the other from a Python script you could use the os.system() function or possibly an instance of the subprocess.Popen() class.

OTHER TIPS

I was trying to do the same thing with a Windows batch file, and it really took me a long time... but here it is:

@echo off
setlocal
set target=%~f2
if not "%target:~-1%"=="\" set target=%target%\
xcopy /t /e /y "%~f1" "%target%"
cd %1
forfiles /s /c "cmd /v:on /s /c set relpath=@relpath&set relpath=!relpath:~3,-1!&if @isdir==FALSE fsutil hardlink create """%target%!relpath!""" @file>nul&if errorlevel 1 echo Failed for !relpath!"
endlocal

It must be run in an elevated command prompt.

Also, all the paths must not include an ! character (exclamation mark). Please post a comment if you know how to handle that!

I wish I could simply leave this as a comment to user1537366, but I need 50 reputation to comment :S

To also make the batch file work with exclamation marks, try the following code:

@echo off

    set source=
    set target=

    forfiles /s /P "%source%" /C "cmd /c if @isdir==TRUE (mklink /j \"%target%\@relpath\" @path ) else (mklink /h \"%target%\@relpath\" @path )"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top