Discussion
It is sometimes useful to refer to the same file by two different names or locations. You can’t solve this problem by copying the item, because modifications to one file do not automatically affect the other.
The solution to this is called a hard link, an item of a new name that points to the data of another file. The Windows operating system supports hard links, but only Windows Vista includes a utility that lets you create them.
Example 176 lets you create hard links without needing to install additional tools. It uses (and requires) the InvokeWindowsApi.ps1 script.
Example 176. NewFilesystemHardLink.ps1
############################################################################## ## ## NewFileSystemHardLink.ps1 ## ## Create a new hard link, which allows you to create a new name by which you ## can access an existing file. Windows only deletes the actual file once ## you delete all hard links that point to it. ## ## ie: ## ## PS >"Hello" > test.txt ## PS >dir test* | select name ## ## Name ## ## test.txt ## ## PS >NewFilesystemHardLink.ps1 test2.txt test.txt ## PS >type test2.txt ## Hello ## PS >dir test* | select name ## ## Name ## ## test.txt ## test2.txt ## ##############################################################################
param( ## The new filename you want to create [string] $filename,
## The existing file that you want the new name to point to [string] $existingFilename )
## Ensure that the provided names are absolute paths
$filename = $executionContext.SessionState.Path.` GetUnresolvedProviderPathFromPSPath($filename)
$existingFilename = ResolvePath $existingFilename
## Prepare the parameter types and parameters for the CreateHardLink function $parameterTypes = [string], [string], [IntPtr] $parameters = [string] $filename, [string] $existingFilename, [IntPtr]::Zero
## Call the CreateHardLink method in the Kernel32 DLL
$currentDirectory = SplitPath $myInvocation.MyCommand.Path
$invokeWindowsApiCommand = JoinPath $currentDirectory InvokeWindowsApi.ps1
$result = & $invokeWindowsApiCommand "kernel32" ` ([bool]) "CreateHardLink" $parameterTypes $parameters
Example 176. NewFilesystemHardLink.ps1 (continued)
## Provide an error message if the call fails if(not $result) {
$message = "Could not create hard link of $filename to " + "existing file $existingFilename" WriteError $message }