- Как создавать и удалять симлинки
- Windows
- Синтаксис
- Симлинк на файл
- Симлинк на директорию
- Удалить симлинк
- Разрешить симлинки в Windows
- Linux и FreeBSD
- Создание
- Использование символических ссылок в Windows
- Как создать символическую ссылку в Windows?
- Как найти и вывести все символические ссылки на диске?
- 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
- How to Use Symlinks in Windows
- Share This Story
- Get our `newsletter`
- DISCUSSION
Как создавать и удалять симлинки
Windows
Работы с символьными ссылками в Windows ведутся из командной строки.
Синтаксис
Симлинк на файл
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\Сетевая папка»
Для файла:
Разрешить симлинки в Windows
Если при попытке перейти по символьной ссылке мы получим ошибку «Символическая ссылка не может быть загружена, так как ее тип отключен», открываем командную строку от администратора и вводим команду:
fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1
Если это не помогло, пробуем создать симлинк с ключом /J.
Linux и FreeBSD
Создание
В системах на базе Linux (например, Ubuntu или CentOS) и FreeBSD симлинк для каталога и файла создаются одинаково:
Использование символических ссылок в Windows
Символическая ссылка (симлинк, символьная ссылка, 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 простой. Чтобы создать символическую ссылку на файл, нужно указать имя ссылки и целевой объект, на который она должна указывать. Можно указать тип ссылки: /D — символьная (мягкая) ссылка на каталог, /H — жесткая ссылка, /J – точка соединения (Junction point).
Если вам нужно разрешить создавать символические ссылки обычным пользователям, нужно добавить группу пользователей в параметр групповой политики Create Symbolic Links (Computer configuration -> Window Settings -> Security settings -> User Rights Assignment в редакторе GPO). По умолчанию в этой политике добавлена только локальная группа «Administrators». Обновите локальные политики после изменения параметра: gpupdate /force
Создадим в каталоге C:\PS символическую ссылку на файл notepad.exe:
mklink C:\PS\note.exe c:\Windows\System32\notepad.exe
Должно появится сообщение:
Теперь для запуска процесса notepad.exe можно использовать символическую ссылку note.exe.
Теперь создадим в этом каталоге симлинк на другой каталог на этом же диcке:
mklink /D “C:\PS\Downloads” “C:\Users\user\Downloads”
Теперь при переходе в каталог C:\PS\Downloads вы будете видеть содержимое каталога, на который он ссылается.
Выведем содержимое каталога C:\PS:
Как вы видите, в атрибутах некоторых файлов указано, что это symlink/simlinkd. Также указан объект, на который они ссылаются. В Windows File Explorer симлинки отображаются с иконками ярлыков, а в их свойствах можно посмотреть целевой объект на который они ссылаются.
Также можно создать символически ссылки в Windows 10 с помощью PowerShell (в этом примере я использую относительные пути, чтобы создать символическую ссылку):
New-Item -ItemType SymbolicLink -Path «.\test\tmpfiles» -Target «..\tmp\files»
Можно создать символическую ссылку на сетевую папку на удаленном компьютере/сервере. Адрес сетевой папки нужно указывать в формате UNC. Следующий пример создаст симлинк на сетевой каталог на сервере:
mklink /D c:\ps\share \\mskfs01\Share
Например, подключим административную шару C$ с удаленного компьютера по IP адресу:
mklink /D c:\remotePC\server1 \\192.168.31.15\С$
Если при доступе к сетевой папке через симлинк, вы получили ошибку
проверьте разрешенные способы использования символических ссылок на вашем компьютере:
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:\ — укажите имя диска, на котором нужно найти все символические ссылки (если вы не хотите сканировать весь диск, укажите путь к нужному каталогу)
Также можно вывести список всех символических ссылок на диске с помощью PowerShell. Для этого нужно просканировать все каталоги и найти NTFS объекты с атрибутом ReparsePoint:
Get-ChildItem -Path C:\ -Force -Recurse -ErrorAction ‘silentlycontinue’ | Where
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.
How to Use Symlinks in Windows
Technology blog Tested goes in depth to explain Windows symlinks (symbolic links that let you do all sorts of cool things like sync files and folders outside your Dropbox folder ), detailing what they are and how to use them.
Sync Files and Folders Outside Your My Dropbox Folder
The popular cross-platform file-syncing application Dropbox is a hit among Lifehacker readers, but…
We’ve talked about how to use symlinks in OS X and Linux in the past, and shown you how to use them for specific things in Windows, but we’ve never gone in depth on Windows symlinks. Tested’s guide nicely explains how to create symlinks in Windows and offers suggestions for when you might benefit from a symlink. For example:
Move Files Without Breaking Stuff
Linux or Mac OS X only: The Command-Line Fu web site writes up a quick-and-dirty trick to move…
mklink /j «c:\users\Will\Music\iTunes\iTunes Music» d:\Music\ — This line makes a symlink that redirects from the folder c:\users\Will\Music\iTunes\iTunes Music to the Music folder on my second hard drive. This type of use is especially handy if you have a small main hard drive and a larger secondary drive.
Granted, in many instances you’ll be better off just changing whatever settings you can so that an application is pointing at the right directory and you don’t need a symlink, but knowing how to set up and use a good symlink can be really handy in the right circumstances.
Share This Story
Get our `newsletter`
DISCUSSION
I would love to see a table comparing the features, advantages and disadvantages of shortcuts vs hardlinks vs symbolic links vs junction points.
Frankly, hardlinks, symlinks, and junction points scare me. I can’t seem to wrap my mind around them and feel comfortable with them. They sound useful, but I would want to use them for folders and would be afraid I was deleting an actual folder rather than just a link.