- Как создавать символические ссылки (Symlinks) в системе Windows
- Что такое символические ссылки
- Как создать символические ссылки с mklink
- Как создать символическую ссылку с помощью графического инструмента
- Как удалить символические ссылки
- How to Create Symbolic Links (Symlink) in Windows 10
- What Are Symbolic Links?
- Create Symbolic Link Using Link Shell Extension
- Create Symbolic Link Using Mklink
- Symlinks in Windows 10!
- Overview
- Background
- What drove this change?
- How to use Symlinks
- How do I try it?
Как создавать символические ссылки (Symlinks) в системе Windows
Windows 10, 8, 7 и Vista поддерживают символические ссылки, которые указывают на файл или папку в вашей системе. Вы можете создать их с помощью командной строки или стороннего инструмента под названием Link Shell Extension.
Что такое символические ссылки
Символические ссылки – это, по сути, расширенные ярлыки. Создайте символическую ссылку на отдельный файл или папку, и эта ссылка будет выглядеть так же, как файл или папка для Windows, хотя это только ссылка, указывающая на файл или папку.
Например, предположим, что у вас есть программа, которая использует файлы в папке C:\Program. А Вам хотелось бы сохранить этот каталог в D:\Refuse, но программа требует, чтобы её файлы были в C:\Program. Вы можете перенести исходный каталог из C:\Program в D:\Refuse, а затем создать символическую ссылку C:\Program, указав на D:\Refuse. Когда вы перезапустите программу, она попытается получить доступ к своему каталогу в C:\Program. Windows автоматически перенаправит её на D:\Refuse, и всё будет работать так, как если бы оно было в C:\Program.
Этот трюк можно использовать для всех целей, включая синхронизацию любой папки с такими программами, как Dropbox, Google Drive и OneDrive.
Существует два типа символических ссылок: жесткая и мягкая. Мягкие символические ссылки работают аналогично стандартным ярлыкам. Когда вы открываете мягкую ссылку на папку, вы будете перенаправлены в папку, где хранятся файлы. Однако, жесткая ссылка заставляет его выглядеть так, как будто файл или папка действительно существуют в местоположении символической ссылки, и ваши приложения не будут знать о подмене. В большинстве ситуаций жесткие символические ссылки более полезны.
Обратите внимание, что Windows фактически не использует термины «жесткая ссылка» и «мягкая ссылка». Вместо этого используются термины «жесткая ссылка» и «символическая ссылка». В документации Windows «символическая ссылка» – это то же самое, что «мягкая ссылка». Тем не менее, mklink-команда может создавать как жесткие ссылки, так и софт-ссылки (известные как «символические ссылки» в Windows).
Как создать символические ссылки с mklink
Вы можете создавать символические ссылки, используя команду mklink в окне командной строки в качестве администратора. Чтобы открыть её, найдите ярлык «Командная строка» в меню «Пуск», щелкните его правой кнопкой мыши и выберите «Запуск от имени администратора».
В Windows Creators Update вы можете использовать обычное окно командной строки, не запуская его как администратор. Однако, чтобы сделать это без окна командной строки администратора, вы должны сначала включить режим разработчика в Параметры → Обновление и безопасность → Разработчики.
Без каких-либо дополнительных опций mklink создает символическую ссылку на файл. Команда ниже создает символическую или «мягкую» ссылку (Link) на объект Target:
Используйте /D, если вы хотите создать символическую ссылку, указывающую на каталог:
Используйте /H, если вы хотите создать жесткую ссылку, указывающую на файл:
Используйте /J для создания жесткой ссылки, указывающую на каталог:
Так, например, если вы хотите создать жесткую ссылку в C:\LinkToFolder, которая указывала бы на C:\Users\Name\OriginalFolder, вы должны выполнить следующую команду:
Вам нужно будет помещать в кавычки пути с пробелами. Например, если папка называется C:\Link To Folder и C:\Users\Name\Original Folder, вы должны использовать следующую команду:
Если вы увидите сообщение «У вас недостаточно прав для выполнения этой операции», Вам следует запустить Командную строку как Администратор.
Как создать символическую ссылку с помощью графического инструмента
Если вы хотите создавать символические ссылки с помощью инструмента с графическим интерфейсом, загрузите Link Shell Extension. Обязательно загрузите соответствующий пакет необходимых библиотек – найдёте их на странице загрузки инструмента.
После установки найдите файл или папку, для которой вы хотите создать ссылку, щелкните её правой кнопкой мыши и выберите «Запомнить источник ссылки» в контекстном меню.
Затем вы можете щелкнуть правой кнопкой мыши в другой папке, указать на меню «Поместить как» и выбрать тип создаваемой ссылки.
Как удалить символические ссылки
Чтобы избавиться от символической ссылки, вы можете просто удалить её, как и любой другой файл или каталог. Только будьте осторожны: удаляйте ссылку, а не файл или каталог, к которому она привязана.
How to Create Symbolic Links (Symlink) in Windows 10
Symlinks or Symbolic Links is one of the lesser known, yet useful, features in Windows. You can think of symbolic links as the shortcuts you create in Windows. However, symbolic links are much more powerful and helpful than regular shortcuts. Let’s discuss what symbolic links are and how you can easily create them in Windows 10.
What Are Symbolic Links?
When you create a shortcut for a file or folder, all you are doing is pointing it to that specific file or folder, nothing more. Symbolic links are much more than a simple shortcut. They act as a virtual file or folder that links to the actual file or folder.
When you create a symlink for a file, it appears as if it is the actual file when in reality it is redirecting you toward the real file in the background. Besides files, you can also create symlinks for folders. Simply put, a symlink is nothing more than a build of the text string which lets the operating system know that it is just a path for another file or folder.
For instance, most cloud service apps you install will only sync files and folders located in their own folder. But there will be times when you might have a folder in some other drive you want to sync with the cloud storage service.
However, you don’t want to move the folder from its actual location or don’t want to create a copy of the folder. In those situations you can simply create a symlink in the cloud service folder so that you can sync the contents of the target folder without actually moving or copying the real folder.
Since a symlink is just a virtual folder that just acts as a path to the real folder, you don’t have to worry about the symlink consuming your disk space.
Create Symbolic Link Using Link Shell Extension
If you don’t want to faff around in the Command Prompt and are prepared to faff around a little bit by installing a tool that lets you create symlinks to an existing file or directory using the right-click context menu, then try the following. Link Shell Extension is a tool that lets you create hardlinks and symbolic links by right-clicking whatever folder you want to create a link to.
There are a few hoops with the installation. You’ll get a warning that it can’t be downloaded securely, and Windows Defender may warn you that it’s “unsigned.”
We can assure you that the tool is safe. Go ahead and install it. During installation, explorer.exe will restart, so make sure you have important stuff backed up.
Once LSE is installed, right-click the target file or folder you want to create a symlink to, then click “Pick Link Source.”
Next, go to the folder where you want the symlink to appear, right-click it, then select “Drop As -> Symbolic Link.”
Create Symbolic Link Using Mklink
Note: though I’m showing this in Windows 10, the commands shown here are applicable to Windows Vista and up.
Creating symlinks in Windows is pretty easy with the mklink command. To start, press Win + X , then select the option “Command Prompt (Admin)” to open the Command Prompt with admin rights.
Once the command prompt has been opened, use the below command format to create a symlink for a file.
In my case, I want to create a symlink in the E drive for a text file located on the F drive, so the command looks something like this:
The first path you see in the above command is where you will create your symlink. This path is called a “Link.” The second path belongs to the actual file on your disk and is called “Target.”
Once the symlink has been created, this is how it looks in the File Explorer. Though the icon looks like a regular shortcut, it is a symlink.
Along with individual files, you can create symlinks for entire directories. To do that, use the below command. The switch /D allows you to do this.
As soon as you execute the command, the symlink will be created for the target directory. You can use it to access all the files and folders inside the real folder. If you ever want to, you can delete the symbolic link like any other file or folder. Just select the symlink, press the delete key on your keyboard, and you are good to go.
And you’re done! If you want to do more under-the-hood tweaking in Windows 10, see our list of the best registry hacks. Also, check out our guide on how to get Mac-style hot corners in Windows 10.
Symlinks in Windows 10!
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.
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 1 st 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
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
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):
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!