How to create links in PowerShell
The purpose of this post is to remind myself how to create links in PowerShell. Nowadays (since mid-August 2016) PowerShell is cross-platform and open-source (with MIT license).
Cmdlets
Commands in PowerShell are called cmdlets. There are two of them to create
links: New-HardLink
for creating hard links and New-Symlink
for creating
symbolic links. Unfortunately, I was not able to get New-Symlink
to work
but see below for workaround.
Hard links
Hard links can be created with New-Hardlink
and work as expected.
❯ echo barbaz > .\foo.txt
❯ New-Hardlink hardfoo.txt foo.txt
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 25/03/2023 13.04 8 hardfoo.txt
❯ cat .\hardfoo.txt
barbaz
echo bazqux > .\hardfoo.txt
bazqux
❯ rm foo.txt
❯ cat .\hardfoo.txt
bazqux
As it is possible to see above, hardfoo.txt
is a hard link, in other words
just an another name for the same file. Removing foo.txt
name does not affect
the file itself.
Symbolic links
As I have mentioned above, I did not manage to create a symbolic link with
New-Symlink
cmdlet. Let me show.
❯ echo foobar > .\foo.txt
❯ New-Symlink .\symfoo.txti .\foo.txt
❯ echo foobar > .\foo.txt
❯ New-Symlink .\symfoo.txt .\foo.txt
❯ ls symfoo.txt
Get-ChildItem: Cannot find path 'C:\Users\XXXXXX\symfoo.txt' because it does not exist.
However, I can create symbolic links with New-Item
cmdlet, and they work:
❯ echo foobar > .\foo.txt
❯ New-Item -ItemType SymbolicLink -Path .\symfoo.txt -Value .\foo.txt
Directory: C:\Users\XXXXXX
Mode LastWriteTime Length Name
---- ------------- ------ ----
la--- 25/03/2023 13.23 0 symfoo.txt -> .\foo.txt
❯ cat .\symfoo.txt
foobar
❯ echo barbaz > .\foo.txt
❯ cat .\symfoo.txt
barbaz
❯ echo bazqux > .\symfoo.txt
❯ cat .\foo.txt
bazqux
❯ rm .\foo.txt
❯ cat .\symfoo.txt
Get-Content: Could not find file 'C:\Users\XXXXXX\symfoo.txt'.
As it is possible to see above, symfoo.txt
is a link to foo.txt
. When the
original file is deleted, the link points to nowhere.
I probably should mention that all that is happening on NTFS.