Creating Hard Links

by Sep 23, 2013

Hard links are file "phantoms" in the NTFS file system. They make one file visible in multiple file system locations (within one volume).

So the file occupies space only where it originally was stored but is also available elsewhere. This can be useful if you must make available large files in multiple file locations.

Here's the function New-HardLink. It illustrates how PowerShell can access low-level API functions:

function New-HardLink


    $signature = '
            public static extern bool CreateHardLink(string lpFileName,string lpExistingFileName,IntPtr lpSecurityAttributes)
    Add-Type -MemberDefinition $signature -Name Creator -Namespace Link 



And here is what you can do with it:

$Original = "$env:temp\testfile.txt"
$Copy1 = "$env:userprofile\Desktop\mirrorfile1.txt"
$Copy2 = "$env:userprofile\Desktop\mirrorfile2.txt"

# create original file:
Set-Content -Path $Original -Value 'Hello'

# create hard link #1:
New-HardLink -OriginalFilePath $Original -MirroredFilePath $Copy1

# create hard link #2:
New-HardLink -OriginalFilePath $Original -MirroredFilePath $Copy2 

The code first creates a physical file in the temp folder. Then, it creates two hard links on your desktop. They appear as mirrorfile1.txt and mirrorfile2.txt, and although they look like separate files, in reality they both point to the temporary file.

You can now open one of the two files on your desktop, make some changes, then save and close. Once you open the other file, the very same updated content appears. You can also simply delete a phantom file to get rid of the hard link.

Twitter This Tip! ReTweet this Tip!