Windows create link to folder

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

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. This tutorial discusses what symbolic links are and shows how you can easily create them in Windows.

Content

  • Create Symbolic Link Using Link Shell Extension
  • Create Symbolic Link Using Mklink
  • Frequently Asked Questions

Also read: Latest Windows 10 and 11 Update Problems and How to Fix Them

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 may be times when you have a folder in some other drive you want to sync with the cloud storage service.

Also read: 4 Easy Ways to Copy a Large Number of Files Quickly in Windows

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 hard links and symbolic links by right-clicking whatever folder you want to create a link to.

Windows Symlink Script

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.

  1. Once LSE is installed, right-click the target file or folder you want to create a symlink to, then click «Pick Link Source.»

Note: in Windows 11, you’ll have to click «Show more options» first before you will see «Pick Link Source» or any of the other right-click menu options below.

Windows Symlink Source
  1. Go to the folder where you want the symlink to appear, right-click it, then select «Drop As -> Symbolic Link.»
Copy Of Untitled

Also read: How to Sort Folders by Size in Windows

Create Symbolic Link Using Mklink

Note: although these instructions are shown using Windows 11, the commands shown here are applicable for Windows Vista and later.

  1. Creating symlinks in Windows is pretty easy with the mklink command. To start, press Win, then search for «Command Prompt.» Right-click on «Command Prompt» in the results, then select «Run as administrator» to open the Command Prompt with admin rights.
Windows Symlink Cmd
  1. Once the command prompt has been opened, use the below command format to create a symlink for a file.
  1. In my case, I want to create a symlink in the C: drive for a text file located on the F: drive, so the command looks something like this:
mklink "C:\Path\Symlink_File.txt" "F:\Real_File.txt"
Windows Symlink Mklink

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

  1. 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.
Windows Symlink Example

Along with individual files, you can create symlinks for entire directories.

  1. To do that, use the below command. The switch /D allows you to do this.
mklink /D "C:\Path\Symlink_Books" "F:\Books"
Windows Symlink Mklinkfolder
  1. 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.
  2. 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.
Windows Symlink Books

Also read: Find and Open Files Using Command Prompt in Windows

Frequently Asked Questions

Why am I getting an error when I try to install links shell extension?

You most likely do not have the right Microsoft Visual C files installed on your computer, probably when using Windows 11. Download and install the 64-bit or 32-bit runtime DLLs from the same page you downloaded Link Shell Extension, then try installing it again.

Why can’t I use Powershell instead of Command Prompt?

PowerShell is now the default terminal in Windows 11, but unfortunately, it does not work with the mklink command, so you’ll have to fall back on the trusty Command Prompt.

Why can’t I create a symlink in the root of the C: drive?

You can only create folders in the root of the C: drive, assuming that «C» is your system drive. To create symbolic links on this drive, you must make a folder for them first.

Image credit: Pexels. All screenshots by Sydney Butler.

Sydney Butler

Sydney Butler is a technology writer with a background in Psychology who has written for a wide variety of technology outlets including How-To-Geek, Online Tech Tips, Helpdesk Geek, 9to5Mac, 9to5Google, and many more.

He has 25 years of technology troubleshooting experience as a technician and user-education practitioner.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

It seems like the junction command has been retired in Windows 10.

You can download junction from Windows SysInternals (which is part of Microsoft):

Junction not only allows you to create NTFS junctions, it allows you to see if files or directories are actually reparse points. Reparse points are the mechanism on which NTFS junctions are based, and they are used by Windows’ Remote Storage Service (RSS), as well as volume mount points.

Please read this Microsoft KB article for tips on using junctions.

Note that Windows does not support junctions to directories on remote shares.


So how do I create junctions or directory symbolic links in Windows 10?

Download junction as instructed above.

Now you can use the following commands.

Create a junction:

junction "C:\Documents and Settings\UserName\My Documents\My Dropbox\My Games" "C:\Documents and Settings\UserName\My Documents\My Games"

Create a directory symbolic link:

mklink /D "C:\Documents and Settings\UserName\My Documents\My Dropbox\My Games" "C:\Documents and Settings\UserName\My Documents\My Games"

You can use either mklink /j or junction in Windows 10 to create junctions.

You can use mklink /d in Windows 10 to create directory symbolic links.

Notes:

  • junction can also list junctions and determine if a file is a junction unlike mklink.

  • mklink is an internal command only available within a cmd shell.

  • By default Administrator privileges are required to create symbolic links.

    It can also be granted to other users. The security setting «Create symbolic links» can be granted at:

      Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment\
    

Examples

Using mklink to create a directory symbolic link:

F:\test>mklink /d test-dir-sym-link test
symbolic link created for test-dir-sym-link <<===>> test

Using mklink to create a junction:

F:\test>mklink /j test-junction test
Junction created for test-junction <<===>> test

Using junction to create a junction:

F:\test>C:\apps\NirSoft\SysinternalsSuite\junction.exe test-junction test

Junction v1.06 - Windows junction creator and reparse point viewer
Copyright (C) 2000-2010 Mark Russinovich
Sysinternals - www.sysinternals.com

Created: F:\test\test-junction
Targetted at: F:\test\test

Further Reading

  • An A-Z Index of the Windows CMD command line — An excellent reference for all things Windows cmd line related.
  • mklink — Create a symbolic link to a directory or a file, or create a hard file link or directory junction.

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

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

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

Логотип LinuxLinux и 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

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

Дмитрий Моск — частный мастер

Была ли полезна вам эта инструкция?

Да            Нет

Download Windows Speedup Tool to fix errors and make PC run faster

At times, you might need to create a link to a file or folder on Windows 11/10 PC. If so, you can follow this article to find out how you can get the hyperlink or path of a specific folder or file in Windows 11 or Windows 10 PC. Let’s say that you want to mention some files in a text document made in Notepad. There are two ways to do that.

  • First, you can enter the file navigation path like this: D drive > Folder-name > File-name.
  • Second, you can follow this guide to get the link within moments. Here we have explained three different methods, and you can follow any one of them to get it done.

To create a link to a file or folder in Windows 11/10, you have the following ways:

  1. From context menu
  2. Using Properties
  3. Using Network access

1] From the context menu

It is probably the easiest way to obtain the link of a file or folder. However, this option is available in Windows 11 only. Therefore, if you are using Windows 11 and want to copy the file path or link, you can find an option in the context menu. To explain more, right-click on the file or folder and choose the Copy as path option.

How to create a link to file or folder in Windows 11/10

Next, you can paste the file path or link anywhere you want.

2] Using Properties

If you are using Windows 10 or any other older version, which doesn’t have the Copy as path option in the right-click context menu, you can follow this method. It is one of the most common, and it’s been there for a long time.

You need to right-click on the file and select the Properties option. Next, copy the Location on the clipboard and paste it somewhere.

How to create a link to file or folder in Windows 11/10

Then, copy the entire file with the file extension and paste it at the end of the file location. For example, if the path is C:\Users\username\Desktop and the file name is my-file.docx, the entire path will look like this:

C:\Users\<username>\Desktop\my-file.docx

After that, you can copy the entire path and paste it anywhere you like.

3] Using Network access

It is a different kind of method, but it works smoothly on any version of Windows. Whether you use Windows 11, Windows 10, or any other, you can follow this guide to copy the file or folder path.

To get started, you need to right-click on the file or folder and select the Give access to > Specific people.

How to create a link to file or folder in Windows 11/10

However, if you use Windows 11, you need to click on the Show more options to find the Give access to menu.

Once the Network access window is opened, click the Share button. If it asks you to turn on the network discovery, you do not need to do that. Instead, click the Cancel button.

Then, you can find a window like this:

How to create a link to file or folder in Windows 11/10

You can click the Copy button to copy the file link in your clipboard.

How do I create a link to a folder in Windows?

To create a link to a folder in Windows 11 or Windows 10, you can follow the aforementioned guide. There are three different methods you can follow to create or get the path or link to a folder or file. The easiest way is by using the Copy as path option in the right-click context menu.

How do I create a link to a file in Windows?

To create a link to a file in Windows, you can go to the Properties menu and copy the Location first. Then, paste the entire file name with the file extension at the end of the location. Once done, you can copy the entire path, which will represent the file or folder you selected.

That’s all! Hope this guide helped.

Read: How to change Copy name extension for Files and Folders in Windows?

When he is not writing about Microsoft Windows or Office, Sudip likes to work with Photoshop. He has managed the front end and back end of many websites over the years. He is currently pursuing his Bachelor’s degree.

  • Windows could not prepare the computer to boot into the next phase of installation
  • Windows create file cmd windows
  • Windows could not start because the following file is missing or corrupt ntoskrnl exe
  • Windows create bootable usb from iso
  • Windows create a symbolic link