Как сделать символическую ссылку windows 10

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

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.

Overview

Symlinks, or symbolic links, are “virtual” files or folders which reference a physical file or folder located elsewhere, and are an important feature built in to many operating systems, including Linux and Windows.

The Windows’ NTFS file system has supported symlinks since Windows Vista.  However, it hasn’t been easy for Windows developers to create symlinks.  In our efforts to continually improve the Windows Developer experience we’re fixing this!

Starting with Windows 10 Insiders build 14972, symlinks can be created without needing to elevate the console as administrator. This will allow developers, tools and projects, that previously struggled to work effectively on Windows due to symlink issues, to behave just as efficiently and reliably as they do on Linux or OSX.

Background

A symlink is essentially a pointer to a file or folder located elsewhere, consumes little space and is very fast to create (compared to copying a file and its contents).

Because of this, developers often replace duplicate copies of shared files/folders with symlinks referencing physical files/folders. Replacing redundant copies of files can save a great deal of physical disk space, and significantly reduce the time taken to copy/backup/deploy/clone projects.

In UNIX-compatible operating systems like Linux, FreeBSD, OSX, etc., symlinks can be created without restrictions.

However, for Windows users, due to Windows Vista’s security requirements, users needed local admin rights and, importantly, had to run mklink in a command-line console elevated as administrator to create/modify symlinks. This latter restriction resulted in symlinks being infrequently used by most Windows developers, and caused many modern cross-platform development tools to work less efficiently and reliably on Windows.

Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.

What drove this change?

The availability and use of symlinks is a big deal to modern developers:

Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.

Git, for example, along with sites like GitHub, has become the main go-to-source code management tool used by most developers today.

picture1

Figure 1: SCM Tool Trends 2004-2016 (Source, Google)

The use of package managers in modern development has also exploded in recent years. For example, node package manager (npm) served ~400 million installs in the week of July 1st 2015, but served more than 1.2 billion installs just one year later – a 3x increase in just one year! In late June 2016, npm served more than 1.7 billion node packages in just seven days!

Figure 2: npm served 1.2Bn downloads in the first week of July 2016

Figure 2: npm served 1.2Bn downloads in the first week of July 2016

There are clear drivers demanding that Windows enables the ability to create symlinks to non-admin users:

  • Modern development projects are increasingly portable across operating systems
  • Modern development tools are symlink-aware, and many are optimized for symlinks
  • Windows developers should enjoy a development environment that is at least the equal of others

How to use Symlinks

Symlinks are created either using the mklink command or the CreateSymbolicLink API

mklink

  • There is no change in how to call mklink.  For users who have Developer Mode enabled, the mklink command will now successfully create a symlink if the user is not running as an administrator.

CreateSymbolicLink

  • To enable the new behavior when using the CreateSymbolicLink API, there is an additional dwFlags option you will need to set:
Value Meaning
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
0x2
Specify this flag to allow creation of symbolic links when the process is not elevated

Example Use

In the example below:

  • A subfolder folder called “animals” containing three files (cat.txt, dog.txt, and fish.txt)
  • (green) The mklink command is executed to create a symlink called “pet.txt” pointing at the “animalsdog.txt” file
  • (blue) When the contents of the current folder are listed, the symlink can be seen (yellow)
  • (purple) When contents of pet.txt are queried, the content of the referenced file (“dog.txt”) is displayed

picture3

Once created, symlinks can be opened, loaded, deleted, etc., just like any other file. Here, the pet.txt symlink is being opened in Notepad (red):

picture4

How do I try it?

This new symlinks support first shipped in Windows 10 Insiders Build 14972, and will be formally delivered in Windows 10 Creators Update. We are also working with the owners of open-source community tools such as Git and npm so they know symlink improvements are coming and can make the necessary changes to better support symlinks on Windows.

We encourage you to take this new feature for a spin and be sure to let us know via the Windows 10 Feedback hub or on Twitter etc. (see below). Please sign up for the Windows Insiders program if you haven’t already to try out symlinks!

Neal, Yosef (@yosefdurr), Rich (@richturn_ms), and Gilles (@khouzam).

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

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

Используемые термины: Симлинк, 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

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

Quick Links

  • How to Create Symbolic Links with mklink

  • How to Create Symbolic Links with a Graphical Tool

  • How to Delete Symbolic Links

Summary

  • Symbolic links are advanced shortcuts in Windows 11 and Windows 10 that can point to a file or folder, redirecting applications to access them as if they were in a different location.
  • There are two types of symbolic links: soft links, which redirect to the location where files are stored, and hard links, which make it appear as though the file or folder exists at the location of the symbolic link.
  • Symbolic links can be created using the mklink command in Command Prompt, with different options for creating symbolic links to files or directories. Alternatively, you can use the Link Shell Extension, a graphical tool, to create symbolic links with more options.

Windows 11 and Windows 10 both support symbolic links — also known as symlinks — that point to a file or folder on your system. You can create them using the Command Prompt or a third-party tool called Link Shell Extension.

What Are Symbolic Links?

Symbolic links are basically advanced shortcuts. Create a symbolic link to an individual file or folder, and that link will appear to be the same as the file or folder to Windows — even though it’s just a link pointing at the file or folder.

For example, let’s say you have a program that needs its files at C:\Program. You’d really like to store this directory at D:\Stuff, but the program requires that its files be at C:\Program. You could move the original directory from C:\Program to D:\Stuff, and then create a symbolic link at C:\Program pointing to D:\Stuff. When you relaunch the program, it will try to access its directory at C:\Program. Windows will automatically redirect it to D:\Stuff, and everything will just work as if it were in C:\Program.

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

There are two type of symbolic links: Hard and soft. Soft symbolic links work similarly to a standard shortcut. When you open a soft link to a folder, you will be redirected to the folder where the files are stored. However, a hard link makes it appear as though the file or folder actually exists at the location of the symbolic link, and your applications won’t know any better. That makes hard symbolic links more useful in most situations.

Note that Windows doesn’t actually use the terms «hard link» and «soft link». Instead, it uses the terms «hard link» and «symbolic link». In the Windows documentation, a «symbolic link» is the same thing as a «soft link». However, the mklink command can create both hard links (known as «hard links» in Windows) and soft links (known as «symbolic links» in Windows).

How to Create Symbolic Links with mklink

You can create symbolic links using the mklink command in a Command Prompt window as Administrator or as a regular user. To do this without an Administrator Command Prompt window, you must first enable Developer Mode from Settings > Update & Security > For Developers.

To open Command Prompt as admin, click the Start button, search «cmd» or «Command Prompt,» then select «Run as Administrator».

Windows 11 doesn’t require administrative privileges to create symbolic links.

Click "Run as Administrator" to launch Command Prompt as admin.

Without any extra options, mklink creates a symbolic link to a file. The below command creates a symbolic, or «soft», link at Link pointing to the file Target :

mklink Link Target

Use /D when you want to create a soft link pointing to a directory. like so:

mklink /D Link Target

Use /H when you want to create a hard link pointing to a file:

mklink /H Link Target

Use /J to create a hard link pointing to a directory, also known as a directory junction:

mklink /J Link Target
Command Prompt window with the arguments for mklink.

So, for example, if you wanted to create a directory junction (a hard link to a folder) at «C:\LinkToFolder» that pointed to «C:\Users\Name\OriginalFolder,» you’d run the following command:

mklink /J C:\LinkToFolder C:\Users\Name\OriginalFolder

You’ll need to put quotation marks around paths with spaces. For example, if the folders are instead named «C:\Link To Folder» and «C:\Users\Name\Original Folder,» you’d use the following command instead:

mklink /J "C:\Link To Folder" "C:\Users\Name\Original Folder"
Command Prompt window with successful hard symbolic link created between &quot;C:\LinktoFolder&quot; and C:\Users\Name\OriginalFolder

If you see the message «You do not have sufficient privilege to perform this operation.», you need to launch the Command Prompt as Administrator before running the command.

If you’re like to do this with a graphical tool, download Link Shell Extension. Be sure to download the appropriate prerequisite package before the tool itself — both are linked to on the tool’s download page.

Once it’s installed, locate the file or folder you want to create a link to, right-click it, and select «Pick Link Source» in the menu.

Right-click target folder in Windows Explorer, then click &quot;Pick Link Source&quot; in the right-click context menu.

You can then right-click inside a different folder, point to the «Drop As» menu and select «Hardlink» to create a hard link to a file, «Junction» to create a hard link to a directory, or «Symbolic Link» to create a soft link to a file or directory.

Right-click in target folder and select &quot;Junction&quot; to create a hard link in that location.

How to Delete Symbolic Links

To get rid of a symbolic link, you can simply delete it like you would any other file or directory. Just be careful to delete the link itself rather than the file or directory it’s linking to.

Right-click the symbolic link and click &quot;Delete&quot; to remove a link.

That is a major advantage of a symbolic link — you can freely delete the symbolic link whenever you want without worrying about the associated files or folders.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Системный журнал windows 10 отключить
  • Bandwidth test mikrotik windows
  • Как удалить временные файлы с компьютера в windows 10
  • Оптимизация pubg windows 10
  • Hyper v windows xp mode