Creating symlinks in windows

Как создать символьную ссылку в Windows 10, 8.1, 8, 7

Товарищи, добрый день. Хотя эта тема и не самая популярная, но она мне очень много раз выручала, поэтому я не могу о ней не написать. Итак, что значит термин «символьная ссылка» я возьму из энциклопедии Wikipedia:

Символьная ссылка (также симлинк от англ. Symbolic link, символическая ссылка) — специальный файл в файловой системе, для которого не формируются никакие данные, кроме одной текстовой строки с указателем. Эта строка трактуется как путь к файлу, который должен быть открыт при попытке обратиться к данной ссылке (файлу). Символьная ссылка занимает ровно столько места в файловой системе, сколько требуется для записи её содержимого (нормальный файл занимает как минимум один блок раздела).

По своей сути же, симлинк — это ярлык, который позволяет системе думать, что это не ярлык, а настоящий файл (или папка). К примеру, частое применение символьной ссылок для папок — это установка игры на SSD, с последующем переносом файлов графики на жесткий диск, с целью экономия места на SSD и создание символьной ссылки до исходного места. Игра будет думать, что все файлы находятся в исходной папке. Так же символьные ссылки можно применять когда используются одинаковые файлы в нескольких каталогах, чтобы не вносить правки во все файлы, можно создать с одного файла символьные ссылки и вносить изменения один раз.

Создать символьную ссылку очень просто и сейчас я вам это докажу. Открываем командную строку, нажимаем Win+R, вводим cmd и жмём ОК. Хотя если вы собираетесь работать с системными файлами, может понадобиться командная строка с правами администратора.

Дальше нам нужно ввести команду для создания символьной ссылки, выглядит она следующем образом:

где /j — атрибут создания соединения для каталога. Если вы создаете ссылку на файл, атрибут ставить не надо.

К примеру, если я хочу создать символьную ссылку на папку mklink на локальном диске E, как папку mk на диске С, мне нужно ввести следующую команду (и да, символьная ссылка может называться не так, как исходный файл (папка):

В результате мы получим вот это.

Если же мы хотим создать символьную ссылку на файл, например на файл 1.txt, хранящийся в корне диска E. для использования в виде файла 2.txt. скажем в папке mslink на диске C, команда будет выглядеть вот так:

А на выходе получим вот это.

Резюмируя скажу, что знание возможностей данной функции, открывает большие возможности. С помощью неё я выходил из нескольких ситуаций, когда не хватало свободного пространства, на моем старом SSD, позволяя быстро перенести игру из папки origin на другой диск. Но вариантов использования её гораздо больше, к примеру перенос кэша браузеров, о котором мы поговорим в одной из будущих статей.

Вроде всё. Надеюсь эта статья оказалась вам полезной, обязательно нажмите одну из кнопок ниже, чтобы рассказать о ней друзьям. Также подпишитесь на обновления сайта, введя свой e-mail в поле справа или подписавшись на группу во Вконтакте и канал YouTube.
Спасибо за внимание

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.

Читайте также:  Linux which directory to backup

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.

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.”

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.

Читайте также:  Где отключить антивирус windows 10

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.

Читайте также:  Самые хорошие приложения windows 10

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

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!

Оцените статью