Mklink 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"}

What is mklink?

mklink is a keyword used to make symbolic-links between directories. Imagine that you wanted to store a directory somewhere and wanted a shortcut to access it from somewhere else. mklink would enable you to achieve this task.

Format

mklink <Option> <Link> <Target>

Link is the path where you want the shortcut/symbolic-link to be, PLUS the name of the shortcut.

Target is the path to the folder you want to link to.

Option provides three parameters to specify the type of link you want to establish.

Symbol Use
/d or /D Creates a soft symbolic link
/h or /H Creates a hard symbolic link
/j or /J Creates a Directory Junction

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

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.

Compared to Linux, Symbolic Links (Symlinks) are a fairly new addition to Windows, first introduced in Windows Vista. They have been present ever since.

Unfortunately, most people don’t know anything about symlinks. Let us take a look at what symlinks are and how to use symlinks in Windows 10.

What Are Symbolic Links?

Symbolic links are shortcuts on steroids. In other words, they act just like regular shortcuts, but they are much more powerful. For instance, when you set up a symbolic link to a file, you can fool programs into thinking the file exists at a location that it doesn’t exist at.

There are two main types of symbolic links on Windows: Hard Links and Soft Links. Unlike Linux, only soft links are called symlinks in Windows.

Hard Links

If you hard-link a file or a folder in location A to a file or a folder in location B, the file or folder at location B would appear as though it exists at location A.

For example, let’s assume that we have a text file called «sample.txt» in the C:\Programs directory. If I hard link sample.txt to a file named «test.txt,» the OS will treat test.txt as though it was sample.txt.

Essentially, all hard links appear as the original file or directory. Consequently, the hard links that you create point to the same storage location on your hard drive. So, if you make any changes to a hard link, the changes will reflect in the original file.

One thing to remember before using hard links is that you can’t create a hard link across different disk drives. So, if you have a file stored in the C: drive, your hard link must also be stored in the C: drive. This is a file system limitation.

Finally, if you have created a hard link for a specific file and you want to delete that file, you also need to delete every hard link. Since a hard link represents the actual file, they point to a storage location on your hard drive. So, to free the storage location, you have to delete every link that points towards it.

Soft Links or Symlinks

Soft Links work just like regular shortcuts. But they differ in one key way: symlinks represent the address of the file rather than the actual file. So, unlike a shortcut, a symlink is not a file. This is also why symlinks take up no space on your hard drive, and shortcuts do.

Contrary to hard links, symlinks don’t point to a storage location on the hard drive. They point to the file or the directory that points to the storage location. So, if you want to delete a file, you don’t have to delete all of the symlinks pointing to that file.

Illustration explaining the difference between hard links and soft links

Symlinks can also be created across different drives because they point to the original file rather than the file’s storage location.

When Should You Use a Symlink?

First, symlinks are faster than traditional shortcuts. Therefore, on a slow computer, you should use symlinks instead of shortcuts.

Second, there are situations when you have to copy/paste a large amount of data from one location to another. In such situations, it is preferable to create a symlink rather than copying and pasting. This can save a lot of storage owing to the lack of duplicate files.

Finally, some programs require you to have files present at a certain location on the storage drive. For instance, OneDrive only syncs files that are present in the OneDrive directory. By using a symlink, you can sync any file regardless of its location on your computer.

Setting Up Symlinks on Windows 10 Using Command Prompt

On Windows 10, you can set up symlinks through the Command Prompt using the mklink command.

First up, launch the Command Prompt by typing cmd in the Start menu search bar, then right-click the Best Match and select Run as administrator.

You can use the mklink command to create hard and soft links. To get an overview of the mklink utility, type mklink and press Enter. This will give you an overview of the mklink utility by listing the command syntax and the different options associated with it.

MKLINK utility overview

Now, let’s create a soft link to a text file using mklink.

Type mklink link target, replacing “link” with the address of the soft link that you want to create, and replace “target” with the address of the original file. The following image shows how to create a soft link named “softlink.txt” that references a file “original.txt.”

MKLINK creating a softlink

If you want to create a soft link to a folder or directory, use the format mklink /D link target. The “/D” option creates a symlink to a directory.

Creating a hard link also follows the same process. Use the same mklink link target command structure but with the “/H” option.

The following image shows how to create a hard link for the fictional “hardlink.txt” file, pointing to the same storage location as “original.txt.”

MKLINK creating hardl ink

If you want to create a hard link to a folder or a directory, use the “/J” option instead of the “/H” option.

Creating Symbolic Links Using Hard Link Shell Extension

To get started, download Hard Link Shell Extension and install it. Make sure to pick the right package for your computer. For instance, if you have a 64-bit OS, download the 64-bit version. Unsure what you’re using? Here’s how to check whether you’re using 64-bit or 32-bit Windows.

After installing the package, navigate to the file or folder you want to create a link. Right-click on the file and select Pick Link Source from the dropdown list.

Creating a link with Hard Link Shell

After picking the link, navigate to the destination folder where you want to create the link. Right-click on an empty area and select Drop Symbolic Link. This will create a symlink with the same name as the original file.

You can use the same method to create a hard link to a file or a folder. Remember that you can only create a hard link within the same disk drive. The Hard Link Shell Extension will only give you the option of creating a hard link if you are on the same disk drive.

After picking the link, right-click anywhere inside the drive, hover over Drop As, and select Hardlink. This will create a hard link to the original file.

Creating a hard link with Hard Link Shell utility

Symbolic Links Can Help You Save a Lot of Storage

Understandably, not everyone will find a use for symbolic links. But for people that like to keep everything tidy while using as little storage as possible, symbolic links are an awesome feature.

So, instead of copying files to different locations, create symbolic links, and you will be good to go.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Gf210 драйвер windows 10 64
  • Значок на рабочем столе windows называют
  • Как распределяется память в разных windows системах
  • Изменить яркость экрана windows 10 cmd
  • Windows 11 update assistant github