Windows create symbolic link file

Символическая ссылка (симлинк, символьная ссылка, 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"}

Как создавать и удалять симлинки

Обновлено:
Опубликовано:

Используемые термины: Симлинк, Windows, Linux.

Windows
Linux
Проблемы и решения

Работы с символьными ссылками в Windows ведутся из командной строки.

Синтаксис

mklink <имя создаваемого симлинка> <на что ведет симлинк>

Симлинк на файл

mklink C:\Users\dmosk\Desktop\cmd.exe C:\Windows\system32\cmd.exe

* в данном примере на рабочем столе пользователя dmosk будет создан симлинк на файл cmd.exe.

Симлинк на директорию

mklink /D «C:\Users\dmosk\Desktop\Сетевая папка» \\dmosk.local\share

* в примере создается симлинк на сетевую папку \\dmosk.local\share
** так как в названии папки есть пробел, путь заключен в кавычки.

Для создания ссылки на папку доступен также ключ /J. Созданная таким образом ссылка будет по некоторым особенностям напоминать жесткую ссылку.

Удалить симлинк

В Windows его можно удалить в проводнике, как обычный файл или папку.

Или использовать командную строку.

Для папки:

rmdir «C:\Users\dmosk\Desktop\Сетевая папка»

Для файла:

del C:\Users\dmosk\Desktop\cmd.exe

Разрешить симлинки в Windows

Если при попытке перейти по символьной ссылке мы получим ошибку «Символическая ссылка не может быть загружена, так как ее тип отключен», открываем командную строку от администратора и вводим команду:

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

Если это не помогло, пробуем создать симлинк с ключом /J.

Linux и FreeBSD

Создание

Общий синтаксис

ln -s <на какой существующий объект будет вести> <создаваемый симлинк>

В системах на базе Linux (например, Ubuntu или CentOS) и FreeBSD симлинк для каталога и файла создаются одинаково:

ln -s /usr/share/nginx/html/index.php /home/dmosk/

ln -s /usr/share/nginx/html /home/dmosk/

* в первом примере создана символьная ссылка в домашней директории пользователя dmosk на файл index.php; во втором — на каталог /usr/share/nginx/html.

Удаление

Также используется одна команда:

rm /home/dmosk/index.php

Решение возможных проблем

При работе с симлинками мы можем сталкиваться с различными проблемами. Я рассмотрю те, с которыми приходилось сталкиваться мне.

ln: failed to create symbolic link … Function not implemented

При попытке создать симлинк мы можем получить ошибку Function not implemented, например:

ln: failed to create symbolic link ‘/etc/pve/nodes/pve/fullchain.pem’: Function not implemented

Причина: файловая система, на которой мы хотим создать файл не поддерживает симлинки. Посмотреть файловую систему подмонтированных разделов можно командой:

df -T

Решение: как правило, решения зависит от используемой файловой системы и ее драйвера. Но, обычно, решения у проблемы нет и нужно искать методы работы без использования символьных ссылок.

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.

On Windows 11 and 10, you can use the built-in “mklink” command to create symbolic links (symlinks) for files and folders. A symbolic link acts as a shortcut (very different from the regular desktop shortcut), linking to a file or folder in one location while the actual content remains stored elsewhere. For example, you can create a symlink to sync any folder with OneDrive without moving the actual folder. Simply put, creating symlinks not only saves space but is an efficient way to manage files and directories across different drives or storage locations.

In this tutorial, I’ll show you how to create symbolic links (symlinks) for files and folders. Let’s get started.

Before You Begin

  • You need administrator rights to create symlinks on Windows.

What Are Symbolic Links (symlinks) and Hard Links?

Before diving in and learning the steps to create symlinks, you need to understand the difference between symbolic links and hard links.

Symbolic Link (Symlink): A symlink is like a shortcut that points to another file or folder on your system. When you open a symlink, it takes you to the actual location of the original file or folder. Any changes made to the original file will appear in the symlink. If you delete the original file, the symlink becomes empty or unusable.

Hard link: A hard link acts like a copy of the original file but points to the same data on the disk. Hard links only work with files (not folders) and must be on the same drive as the original file. Changes to either the hard link or the original file reflect in the other, as both point to the same data. Unlike symlinks, deleting the original file does not break the hard link, as the data remains accessible through the link.

Create a Symlink for a File or Folder

  1. Right-click on the Start button.
  2. Select the “Terminal (Admin)” option.
  3. Click the down arrow on the title bar.
  4. Select the “Command Prompt” option.
  5. Run the following command to create a symlink to a folder. mklink /D "C:\path\to\LinkFolder" "D:\path\to\ActualFolder"
  6. Run the following command to create a symlink to a file. mklink "C:\path\to\LinkFile.txt" "D:\path\to\ActualFile.txt"
  7. With that, you’ve created the symlink for a file or folder on Windows.

Detailed Steps (With Screenshots)

First, open the terminal window with administrative privileges. To do that, right-click the Start button on the taskbar and choose the “Terminal (Admin)” option.

open Windows terminal as admin Windows 11

In the terminal window, open the Command Prompt tab by clicking the dropdown icon on the title bar and selecting the “Command Prompt” option.

Note: The below command doesn’t work in the PowerShell tab.

open Command Prompt in terminal

run the following commands to create a symlink.

In the command, replace the first path with the path where you want the symlink to appear and the second path with the actual file or folder path that you are linking.

  • Symlink to a file
mklink "C:\path\to\LinkFile.txt" "D:\path\to\ActualFile.txt"
  • Symlink to a folder
mklink /D "C:\path\to\LinkFolder" "D:\path\to\ActualFolder"
run mklink command to create symlink

That is it. As soon as you execute the above command, Windows creates a symlink in the location and name of your choice. If you open the File Explorer and go to the drive/folder where you saved the symlink, you will see it immediately.

symlink in action

Wrapping Up — Creating Symlinks on Windows

As you can see, thanks to the built-in mklink command, you can easily create a symlink to any file or folder with just a single-line command. Do keep in mind that, any changes you make to the symlink will reflect in the original file or folder. Also, if you delete the original file or folder, the symlink will no longer work.

If you have any questions or need help, comment below. I’ll be happy to assist.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Qemu system x86 64 windows 7
  • Kodi медиацентр для windows
  • Не могу включить wifi на ноутбуке windows 10
  • Топ консолей для windows
  • Minecraft windows 10 edition beta appx