Windows create symlink to directory

Символическая ссылка (симлинк, символьная ссылка, Symbolic link) это специальный файл на файловой системе, которые сам не содержит данных, а является по сути ярлыком, указывающим на какой-то другой объект (файл или папку). При обращении к симлику операционная система считает, что это оригинальный файл (папка) и работает с ними совершенно прозрачно.

Символические ссылки используются в Windows довольно часто для системных файлов и каталогов. Пользователь может их применять, когда нужно перенести часть “тяжелых” файлов на другой диск, но чтобы Windows считала, что файлы все еще находятся в исходном каталоге (например в ситуациях, когда нужно экономить место на SSD, перенеся некоторые каталоги на более медленный и емкий SSD, не нарушая работоспособности программ). Можно использовать симлинки на SMB файловом сервере, когда каталоги с разных LUN должны быть доступны через одну точку входа.

В Windows есть три типа файловых ссылок для NTFS томов: жесткие, мягкие (симлинки), точки соединения (Junction point).

  • Hard Links (жесткие ссылки) – могут указывать только на локальный файл, но не на папку. Такой файл – это ссылка на другой файла на этом же диске без фактического дублирования самого файла. У него отображается такой же размер и свойства, как у целевого файла (но реальное место на диске он не занимает);
  • Junction Points (Directory Hard Link, точка соединения) – могут указывать только на папку (на этом же или на другом разделе);
  • Symbolic Links (мягкая ссылка, симлинк) – могут указывать на локальный файл, папку и сетевой каталог на удаленном компьютере (UNC), поддерживаются относительные пути.

В подавляющем большинстве случаев вам будет достаточно функционала symbolic link, как наиболее универсального средства создания ссылки на любой объект.

Как создать символическую ссылку в Windows?

Для создания символических и жестких ссылок в Windows можно использовать встроенную утилиты mklink или PowerShell.

mklink утилита для создания симлинков в windows

Синтаксис у утилиты
mklink
простой. Чтобы создать символическую ссылку на файл, нужно указать имя ссылки и целевой объект, на который она должна указывать. Можно указать тип ссылки:
/D
— символьная (мягкая) ссылка на каталог,
/H
— жесткая ссылка,
/J
– точка соединения (Junction point).

Чтобы использовать mklinkдля создания символических ссылок нужно запустить командную строку с правами администратора. Иначе при запуске команды появится ошибка “
You do not have sufficient privilege to perform this operation
”.

Если вам нужно разрешить создавать символические ссылки обычным пользователям, нужно добавить группу пользователей в параметр групповой политики Create Symbolic Links (Computer configuration -> Window Settings -> Security settings -> User Rights Assignment в редакторе GPO). По умолчанию в этой политике добавлена только локальная группа «Administrators». Обновите локальные политики после изменения параметра: gpupdate /force

параметр групповой политики Create Symbolic Links

Создадим в каталоге C:\PS символическую ссылку на файл notepad.exe:

mklink C:\PS\note.exe c:\Windows\System32\notepad.exe

Должно появится сообщение:

symbolic link created for C:\PS\note.exe <<===>> c:\Windows\System32\notepad.exe

Теперь для запуска процесса notepad.exe можно использовать символическую ссылку note.exe.

Теперь создадим в этом каталоге симлинк на другой каталог на этом же диcке:

mklink /D “C:\PS\Downloads” “C:\Users\user\Downloads”

пример использования mklink для создание символьных ссылок в windows

Теперь при переходе в каталог C:\PS\Downloads вы будете видеть содержимое каталога, на который он ссылается.

символическая ссылка на каталог в windows

Выведем содержимое каталога C:\PS:

Dir c:\ps

Как вы видите, в атрибутах некоторых файлов указано, что это symlink/simlinkd. Также указан объект, на который они ссылаются. В Windows File Explorer симлинки отображаются с иконками ярлыков, а в их свойствах можно посмотреть целевой объект на который они ссылаются.

Dir вывести информацию о всех symlink в папке

Также можно создать символически ссылки в Windows 10 с помощью PowerShell (в этом примере я использую относительные пути, чтобы создать символическую ссылку):

New-Item -ItemType SymbolicLink -Path ".\test\tmpfiles" -Target "..\tmp\files"

создать SymbolicLink с помощью powershell

Можно создать символическую ссылку на сетевую папку на удаленном компьютере/сервере. Адрес сетевой папки нужно указывать в формате UNC. Следующий пример создаст симлинк на сетевой каталог на сервере:

mklink /D c:\ps\share \\mskfs01\Share

Например, подключим административную шару C$ с удаленного компьютера по IP адресу:

mklink /D c:\remotePC\server1 \\192.168.31.15\С$

Если при доступе к сетевой папке через симлинк, вы получили ошибку

The symbolic link cannot be followed because its type is disabled

проверьте разрешенные способы использования символических ссылок на вашем компьютере:

fsutil behavior query SymlinkEvaluation

Local to local symbolic links are enabled.
Local to remote symbolic links are enabled.
Remote to local symbolic links are disabled.
Remote to remote symbolic links are disabled.

fsutil behavior query SymlinkEvaluation

Чтобы включить использование символических ссылок на удаленные ресурсы, выполните команды:

fsutil behavior set SymlinkEvaluation R2R:1
fsutil behavior set SymlinkEvaluation R2L:1

Вы можете работать с символическими ссылками, как с обычными объектами файловой системы, можно переименовать, переносить или удалить их. Система автоматически изменит настройки таких симлинков, чтобы они указывали на верные целевые объекты.

Для удаления симлинков используются обычные команды, как и для удаления файлов:

Del c:\ps\note.exe
RD c:\ps\downloads

Как найти и вывести все символические ссылки на диске?

В Windows нет простых инструментов для просмотра и управления всеми симлинками на диске.

Вы можете вывести список всех символических ссылок на диске с помощью команды:

dir /AL /S C:\ | find "SYMLINK"

  • /A
    – вывести файлы с атрибутом L (симлинк);
  • /S
    –выполнить команду рекурсивно для всех вложенных каталогов;
  • C:\
    — укажите имя диска, на котором нужно найти все символические ссылки (если вы не хотите сканировать весь диск, укажите путь к нужному каталогу)

вывести все симлинке на диске в windows

Также можно вывести список всех символических ссылок на диске с помощью PowerShell. Для этого нужно просканировать все каталоги и найти NTFS объекты с атрибутом ReparsePoint:

Get-ChildItem -Path C:\ -Force -Recurse -ErrorAction 'silentlycontinue' | Where { $_.Attributes -match "ReparsePoint"}

A symbolic link (symlink) is a special file on a file system that doesn’t contain any data but is actually a shortcut pointing to another object (file or folder). When accessing a symlink, the operating system thinks that it is an original file (folder) and works with it completely transparently.

Symbolic links are quite often used in Windows for system files and directories. You may use them when you need to move large files to another disk and Windows must consider that they are still located in the original directory (for example, when you want to save space on an SSD by moving some directories to a slower and larger HDD without disrupting programs). You can use symlinks on your SMB file server when directories located in different LUNs must be available in a single entry point.

The three types of file links available in Windows for NTFS volumes: hard links, soft links (symlinks), and Junction Points.

  • Hard Links can only point to a local file, but not to a folder. A hard link is a file link to another file on the same volume without duplicating the file. It has the same size and properties as the source file (but it does not take up real space on the drive);
  • Junction Points (Directory Hard Link) can only point to a directory (on the same or another volume);
  • Symbolic Links (soft link, symlink) can point to a local file, folder, or network share on a remote computer (by the UNC path). Relative paths are supported.

In most cases, you can use a symlink for most tasks when you need to create a reference to an object.

How to Create a Symbolic Link in Windows?

To create symbolic or hard links in Windows, you can use the built-in mklink tool or PowerShell.

mklink has a simple syntax. To create a symbolic link to a file, specify the link name and the target object you want it to point to. You can set the link type: /D — a symbolic (soft) link to a directory, /H — a hard link, /J – a Junction point.

In order to use mklink for creating symbolic links, run the command prompt as administrator. Otherwise, when you run the command, the following error will appear: You do not have sufficient privilege to perform this operation.

If you want to allow non-admin users to create symbolic links, add the user group to Create Symbolic Links GPO option (Computer Configuration -> Window Settings -> Security Settings -> User Rights Assignment in the GPO editor). By default, only the local Administrators group is added to the policy. Update local Group Policy after changing the setting: gpupdate /force

GPO: Allow to Create Symbolic Links

Create a symbolic link to the notepad.exe file in C:\PS:

mklink C:\PS\note.exe c:\Windows\System32\notepad.exe

You will see the following message:

symbolic link created for C:\PS\note.exe <<===>> c:\Windows\System32\notepad.exe

Now you can use the note.exe symlink to run notepad.exe.

Create a symlink to another folder on the same drive:

mklink /D "C:\PS\Downloads" "C:\Users\user\Downloads"

Windows cmd: symbolic link created for ...

Now, when you open the C:\PS\Downloads folder you will see the contents of the directory it refers to.

Display the contents of C:\PS:

dir c:\ps

As you can see, the attributes of some files show that it is a symlink (simlinkd). The object they refer to is also displayed. In File Explorer, symlinks are displayed as shortcut icons, and the target object they point to is shown in their properties.

You can also create a symbolic link in Windows using PowerShell (in this example I use relative paths to create symlink):

New-Item -ItemType SymbolicLink -Path ".\test\tmpfiles" -Target "..\tmp\files"

Create Symbolic Link in Windows with PowerShell

You can create a symbolic link to a shared network folder on a remote computer or server. Specify the network share address in the UNC format.

mklink /D c:\ps\share \\hq-fs01\Share

For example, let’s connect the administrative share C$ on a remote computer using its IP address:

mklink /D c:\remotePC\server1 \\192.168.13.10\C$

If you see the following error when accessing a share using a symlink:

The symbolic link cannot be followed because its type is disabled.

Check the allowed ways of using symbolic links on your computer:

fsutil behavior query SymlinkEvaluation

Local to local symbolic links are enabled.
Local to remote symbolic links are enabled.
Remote to local symbolic links are disabled.
Remote to remote symbolic links are disabled.

fsutil behavior query SymlinkEvaluation

To enable symbolic links to remote resources, run the following commands:

fsutil behavior set SymlinkEvaluation R2R:1
fsutil behavior set SymlinkEvaluation R2L:1

You can work with symbolic links in the same way as with ordinary file system objects: move, rename, or delete them.  Windows will automatically change the settings of the symlinks so that they point to the correct targets.

To remove symlinks, the usual commands are used (like you do for files):

Del c:\ps\note.exe
RD c:\ps\downloads

How to Find All Symbolic Links on a Windows Drive?

There are no built-in tools in Windows to view and manage all symlinks on a disk.

You can list all symbolic links on a disk using this command:

dir /AL /S C:\ | find "SYMLINK"

  • /A – to display files with L attribute (symlinks)
  • /S –run the command recursively for all subfolders
  • C:\ — specify a drive name or path to a folder to search for symlinks

How to List All Symlinks in the Windows Directory or Drive

You can also get a list of all symbolic links on a disk using PowerShell. Just scan all folders and find NTFS objects with the ReparsePoint attribute:

Get-ChildItem -Path C:\ -Force -Recurse -ErrorAction 'silentlycontinue' | Where { $_.Attributes -match "ReparsePoint"}

Last Updated :
08 Sep, 2020

A symbolic link is used to describe a file, that doesn’t store any data. Symbolic Links on Windows contains a reference to another file or directory in the respective of an absolute or you can say to the relative path. The type of path (relative/absolute) is defined during the creation of the link. 

Most operating systems offer support for Symbolic Links in one way or another. Linux and Windows both provide support for generic Symbolic Links with some OS exclusive features, i.e. Windows allows for the creation of Junction points which are folder soft links with a little different working. In this article, we will take a look at the creation of symbolic links on Windows using mklink command found in the command processor (cmd) of the OS. 

Note –

The command requires administrator privileges to execute.

Types of symlinks : 

  • Hard Links 
  • Soft Links

Description of the command : 

MKLINK [[/D] | [/H] | [/J]] Link Target

       /D      Creates a directory symbolic link.  Default is a file
               symbolic link.
       /H      Creates a hard link instead of a symbolic link.
       /J      Creates a Directory Junction.
       Link    Specifies the new symbolic link name.
       Target  Specifies the path (relative or absolute) that the new link
               refers to.

Note –

The above text could be obtained by executing the mklink command without any arguments.

Creating a soft link to a file :

In order to create a soft link, the syntax of the command is:

mklink Link_path Target_path
  • Where Link_path is the name (or path) to the symbolic link which is to be created. 
  • Target_path is the path which the new link will refer to.

Example –

There exists the a file with the path C:\suga\settings

In order to create a soft link of the file on the same path with a different name (ex. apple), the command would look as follows.

mklink  "C:\suga\apple" "C:\suga\settings" 

Note –

In the above command, both paths are absolute.

After the execution of the above command, a soft link to the file will be created appears as follows.

The same method could be used for creating a soft link to a directory as well, the only difference being that the /D switch needs to be added to the command.

making the syntax :

mklink /D Link_path Target_path

Creating a hard link to a file :

In order to create a soft link, the syntax of the command is as follows.

mklink /H Link_path Target_path

Example –

In this example, we would use the same file as the one used in the last example, located at  C:\suga\settings. In order to create a hard link of the file at the same path with a different name (ex. moba) the command would look as follows:

mklink /H "C:\suga\moba" "C:\suga\settings" 

After the execution of the above command, a hard link to the file will be created appearing as follows :

Hard links could not be created for directories, therefore unlike the previous example, both paths (Link & Target) should point to a file only.

Did you know that Windows has supported symlinks since Vista? You can create them using the Windows Command Prompt.

🔗 What Are Symlinks?

Symbolic Links are basically advanced shortcuts that you create on the command line. Once created, Windows treats them just the same as if they were a normal folder.

For example, let’s say you have a program that needs its files at C:\MyProgram, but your C: Drive is dangerously low on space and you’d prefer to install that program on another drive, but it throws errors whenever you try to install it there. For the sake of this argument, we’re going to pretend that the installer will allow you to install to an existing directory — so that one way you could solve this problem would be to create a folder called D:\Stuff\MyProgram, and then create a symbolic link at C:\MyProgram which points to D:\Stuff\MyProgram. Now, once you’ve installed the program and launch it, when it tries to access C:\MyProgram, Windows will automatically redirect it to D:\Stuff\MyProgram, and your program will never know the difference!

This trick can be used for all sorts of things — including syncing any folder with programs such as Dropbox, Google Drive, and OneDrive.

There are two types of Symbolic Link — Hard and Soft. Soft Symbolic Links work similarly to a Windows Shortcut. When you open a soft link to a folder, you will be redirected to the folder where the files are stored — which would probably not be suitable in our example above. A hard link, however, makes it appear as though the file or folder actually exists at the location of the symbolic link, and your applications won’t know the difference. I find myself using hard links as my default in most situations — but you can make up your own minds as to which you want to use where.

Windows uses slightly different terms here though. Instead of «hard link» and «soft link», Windows uses the terms «hard link» and «symbolic link». According to the Windows documentation, a «symbolic link» is exactly the same as a «soft link», and the mklink command is what you need to use to create both kinds.

💻 Creating Symbolic Links with mklink

Firstly, open a Command Prompt in Administrator Mode:

  • Click on the Start button
  • Scroll down to the Windows System folder in the Start Menu
  • Right-click on the Command Prompt shortcut and select Run as Administrator

By default (without any additional options), the mklink command will create a Symbolic Link (or «soft link») to a FILE. The command below creates a symbolic («soft») link at <link> pointing to <target> (you know NOT to type the angle brackets, right?):

To create a symbolic («soft») link to a target DIRECTORY, use the /D option:

mklink /D <link> <target>

To create a «hard link» to a FILE, use:

mklink /H <link> <target>

And to create a «hard link» to a DIRECTORY (also known as a «directory junction»), use:

mklink /J <link> <target>

So, for example, if you wanted to create a directory junction («hard link» to a folder) at C:\LinkToFolder which points at C:\Users\Username\TargetFolder, you’d use the following command:

mklink /J C:\LinkToFolder C:\Users\Username\TargetFolder

If any of your paths have spaces in them, just put quotation marks around them:

mklink /J "C:\Link To Folder" "C:\Users\Username\Target Folder"

If you see the error message «You do not have sufficient privilege to perform this operation», it means that you haven’t launched the Command Prompt (or whatever it is you’ve used) as an Administrator before running the command … (which means you’re rushing things and need to slow down a little, because I DEFINITELY told you that in the first step!)

🚫 Deleting Windows Symlinks

The good news is that Windows Symlinks can be deleted just like any other file or folder from the Command Prompt, Windows Explorer, and any third-party package you might care to use.

The mklink command is a powerful tool in the Windows command line that allows you to create symbolic links. A symbolic link is a special type of file that points to another file or directory on your system. When you access the symbolic link, it behaves as if you are accessing the target file or directory, even though the two are technically separate.

There are two types of symbolic links:
file symbolic links and directory symbolic links.

File symbolic links point to a specific file, while directory symbolic links point to a directory. You can use the mklink command with the /D flag to create a directory symbolic link.
To use the mklink command with the /D flag, open a command prompt window and type the following:

mklink /D <link> <target>

Replace <link> with the path and name of the symbolic link you want to create, and <target> with the path of the target directory.
For example, to create a symbolic link at C:\link_to_documents that points to the D:\documents directory, you would use the following command:

mklink /D C:\link_to_documents D:\documents

When you access the C:\link_to_documents directory, it will behave as if you are accessing the D:\documents directory, even though the two are technically separate.

It’s important to note that creating symbolic links requires administrator privileges. You may need to run the mklink command from an elevated command prompt to create the symbolic link.
There are many uses for symbolic links, such as creating a shortcut to a frequently accessed directory or consolidating multiple directories into one location. The mklink command with the /D flag is a handy tool to have in your toolkit when working with directories in Windows.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Чем записать образ linux на флешку из под windows
  • Как зайти в панель автозапуска windows 10
  • Archive org windows 8 russian
  • Как проверить звуковую карту на компьютере windows 10
  • Темы для панели задач windows 11