Создание символической ссылки windows 10 powershell

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

In Windows 10, you can using symbolic links to easily redirect one folder to another location. Symbolic links are widely used in the operating system for its own files and folders. Using symbolic links, you can save your disk space and make your data accessible from various file system locations without physically moving your data.

Symbolic links can be pretty useful in many situations. For example, some time ago I added an SSD drive to my computer and installed Windows there. All my portable apps remained in the D:\portable folder and many of them were configured to work with the folder D:\documents. The problem was that before I added this new SSD, the path to folders was C:\portable and C:\documents.

By symlinking these two folders I got everything working within a few seconds. I created symbolic links named c:\portable and c:\documents without moving a single file or folder. Another interesting thing is that if I move my symbolic links to some other location, for example, to the E: drive, they continue to work and will point to my folders on the D: drive.

In a previous article, we saw how to manage symbolic links with the built-in mklink console tool. Today, we will see how the same can be done using PowerShell.

  1. Open an elevated PowerShell.
  2. Type or copy-paste the following command:
    New-Item -ItemType SymbolicLink -Path "Link" -Target "Target"
  3. Replace the Link portion with the path to the symbolic link you want to create (including the file name and its extension for files).
  4. Replace the Target portion with the path (relative or absolute) that the new link refers to.
    PowerShell Create Symbolic Link

You are done.
Besides that, you can use PowerShell to create directory junctions and hard links. Let’s see how it can be done.

To Create a Directory Junction in Windows 10 with PowerShell,

  1. Open an elevated PowerShell.
  2. Type or copy-paste the following command:
    New-Item -ItemType Junction -Path "Link" -Target "Target"
  3. Replace the Link portion with the path to the directory junction you want to create.
  4. Replace the Target portion with the full path to the directory that the new link refers to.
    PowerShell Create Directory Junction

To Create a Hard Link in Windows 10 with PowerShell,

  1. Open an elevated PowerShell.
  2. Type or copy-paste the following command:
    New-Item -ItemType HardLink -Path "Link" -Target "Target"
  3. Replace the Link portion with the full path, including the file name and its extension for the hard link you want to create.
  4. Replace the Target portion with the full path to the file that the new link refers to.
    PowerShell Create Hard Link

Now you may wonder what is the difference between a directory symbolic link and a directory junction.

What is the difference between a directory symbolic link and a directory junction
A Directory Junction is an older type of symbolic link, which does not support UNC paths (network paths that begin with \\) and relative paths. Directory junctions are supported in Windows 2000 and later NT-based Windows systems. A directory symbolic link on the other hand also supports UNC and relative paths. However, they require at least Windows Vista. So, in most cases today, the directory symbolic link is the preferred option.

What is the difference between a hard link and a symbolic link
A hard link can be created only for files, not folders. You cannot create a hard link for directories. So, it has more limitations than a Directory Junction and also does not support UNC paths.

In Windows Vista and later, directory junctions are used to link older file folder paths like C:\Documents and Settings to newer paths like C:\Users. Symbolic links are also used to redirect C:\Users\All Users to C:\ProgramData.

Starting with Windows Vista, hard links are also widely utilized by Windows and its Servicing mechanism. Many system files are hard links to files inside the Windows Component Store folder. If you run the command fsutil hardlink list for explorer.exe, notepad.exe or regedit.exe, you can see this yourself!

Windows 10 system hard links

The WinSxS folder stores various system files, which are linked via hard links to the files located in the folders C:\Windows, C:\Windows\System32 and other system folders. When operating system updates are installed, the files inside WinSxS are updated and hard linked to system locations again.

That’s it.

Support us

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!

Недавно мне понадобилось создать через Deployment Workbench в Task Sequense ярлыки на рабочем столе пользователей при установке Windows 10. Казалось что может быть проще? На самом деле пришлось повозиться.

Я всегда думал, что символическая ссылка и обыкновенный ярлык в проводнике Windows — это одно и тоже. Чем же отличаются ярлык и символическая ссылка?

  1. для создания символической ссылки требуются права администратора
  2. если скопировать символическую ссылку в другую директорию, то вместо символической ссылки окажется файл, на который ссылается ссылка, но без расширения. Например сделаем так:
    cp "Internet Explorer" .\test2\
    и вот что можно увидеть в папке test2
  3. В проводнике Windows отображает эти ресурсы по-разному:
    Поэтому для сценариев развертывания Windows лучше всего подойдет возможность создания ярлыков: их можно и скопировать и прав администратора они не будут запрашивать. Создавать только их сложнее: необходимо вписать следующие строчки в ваш скрипт:
    $Install_Path = "C:\Users\AVIvanov\Desktop\test"
    $WSShell = New-Object -com WScript.Shell
    $ShortcutPath = Join-Path -Path $Install_Path -ChildPath "Internet Explorer.lnk"
    $NewShortcut = $WSShell.CreateShortcut($ShortcutPath)
    $NewShortcut.TargetPath = "C:\Program Files\Internet Explorer\iexplore.exe"
    $NewShortcut.Save()
    Так мы создадим ярлык на Internet Explorer в папке «test» на моем рабочем столе.

    Если нужно создать ярлык на URL-адрес, то это будет выглядеть немного по другому:
    $Install_Path = "C:\Users\AVIvanov\Desktop\test"
    $WSShell = New-Object -com WScript.Shell
    $ShortcutPath = Join-Path -Path $Install_Path -ChildPath "Яндекс.url"
    $NewShortcut = $WSShell.CreateShortcut($ShortcutPath)
    $NewShortcut.TargetPath = "https://yandex.ru"
    $NewShortcut.Save()

    Ещё пример: скрипт, который будет открывать в Google Chrome сайт mail.ru:
    $Install_Path = "C:\Users\onix\Desktop"
    $WSShell = New-Object -com WScript.Shell
    $ShortcutPath = Join-Path -Path $Install_Path -ChildPath "MAILRU.lnk"
    $NewShortcut = $WSShell.CreateShortcut($ShortcutPath)
    $NewShortcut.TargetPath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
    $NewShortcut.Arguments = "https://mail.ru"
    $NewShortcut.Save()

    Если кому-то все же понадобится создать именно символическую ссылку через powershell, то такая возможность появилась совсем недавно в Windows 10 1703:
    New-Item -Path "C:\Users\AVIvanov\Desktop\test\Internet Explorer" -value "C:\Program Files\Internet Explorer\iexplore.exe" -ItemType symboliclink -в той же папка «test» на рабочем столе

Skip to content

Powershell – Creating a symbolic link

Powershell – Creating a symbolic link

Would you like to learn how to create a symbolic link using Powershell? In this tutorial, we are going to show you how to use Powershell to create a symbolic link on a computer running Windows.

• Windows 2012 R2
• Windows 2016
• Windows 2019
• Windows 10
• Windows 7

Equipment list

The following section presents the list of equipment used to create this tutorial.

As an Amazon Associate, I earn from qualifying purchases.

Related tutorial – PowerShell

On this page, we offer quick access to a list of tutorials related to PowerShell.

Tutorial Powershell – Creating a symbolic link

As an Administrator, start an elevated Powershell command-line.

Windows 10 - powershell elevated

Create a symbolic link to a directory.

Here is the command output.

In our example, a symbolic link named LINK was created on the root of drive C.

In our example, the symbolic link destination is the directory named SOURCE on the root of drive C.

Congratulations! You are able to create a symbolic link using Powershell.

Tutorial Powershell – Creating a directory junction

As an Administrator, start an elevated Powershell command-line.

Windows 10 - powershell elevated

Create a directory junction link.

Here is the command output.

In our example, a directory junction link named LINK was created on the root of drive C.

In our example, the directory junction link destination is the directory named SOURCE on the root of drive C.

Congratulations! You are able to create a directory junction using Powershell.

Tutorial Powershell – Creating a hard link

As an Administrator, start an elevated Powershell command-line.

Windows 10 - powershell elevated

Create a hard link to a file.

Here is the command output.

In our example, a hard link named LINK was created on the root of drive C.

In our example, the hard link destination is a text file named TEST.

Congratulations! You are able to create a Hard link using Powershell.

VirtualCoin CISSP, PMP, CCNP, MCSE, LPIC22021-05-06T23:37:04-03:00

Related Posts

Page load link

This website uses cookies and third party services.

Ok

  1. What Are Symbolic Links?

  2. Creating Symbolic Links in PowerShell

  3. Creating Directory Junctions

  4. Creating Hard Links

  5. Conclusion

  6. FAQ

How to Create Symbolic Links in PowerShell

Creating symbolic links in Windows PowerShell can seem daunting at first, but it’s a powerful feature that can streamline your workflow. Symbolic links, or symlinks, allow you to create a reference to a file or directory, making it easier to manage your files without duplicating them.

In this article, we’ll explore how to create symbolic links using PowerShell, as well as touch on other types of links like directory junctions and hard links. Whether you’re a seasoned developer or just starting out, understanding these concepts can enhance your file management capabilities in Windows. Let’s dive in!

What Are Symbolic Links?

Before we jump into creating symbolic links, it’s essential to understand what they are. A symbolic link is essentially a pointer to another file or directory. When you access a symlink, the operating system redirects you to the target file or directory. This can be particularly useful for organizing projects or managing dependencies in a development environment.

In PowerShell, you can create symbolic links using the New-Item cmdlet. You can also create directory junctions and hard links, which serve different purposes. While symbolic links are flexible, directory junctions are limited to directories on the same volume, and hard links can only be created for files.

Creating Symbolic Links in PowerShell

To create a symbolic link in PowerShell, you can use the following command:

New-Item -Path "C:\Path\To\Link" -ItemType SymbolicLink -Target "C:\Path\To\Target"

In this command:

  • -Path specifies where you want the symbolic link to be created.
  • -ItemType SymbolicLink indicates that you are creating a symlink.
  • -Target specifies the location of the file or directory you want to link to.

Output:

Symbolic link created successfully.

This command creates a symbolic link at the specified path that points to the target file or directory. You can verify its creation by navigating to the link location and checking its properties. Symbolic links are versatile and can be created for both files and directories.

Creating Directory Junctions

Directory junctions are similar to symbolic links but are specifically designed for directories. They are useful for creating links that point to directories on the same volume. To create a directory junction in PowerShell, you can use the following command:

New-Item -Path "C:\Path\To\Junction" -ItemType Junction -Target "C:\Path\To\TargetDirectory"

In this command:

  • -ItemType Junction specifies that you are creating a directory junction.
  • The -Target parameter points to the directory you want to link to.

Output:

Directory junction created successfully.

Directory junctions can be beneficial when you want to access a directory from multiple locations without duplicating the data. However, keep in mind that junctions can only link to directories on the same volume, which can limit their use in certain scenarios.

Creating Hard Links

Hard links are another type of link that allows you to create multiple references to the same file. Unlike symbolic links, hard links point directly to the file’s data on the disk. To create a hard link in PowerShell, you can use the following command:

New-Item -Path "C:\Path\To\HardLink" -ItemType HardLink -Target "C:\Path\To\TargetFile"

In this command:

  • -ItemType HardLink specifies that you are creating a hard link.
  • The -Target parameter points to the file you want to link to.

Output:

Hard link created successfully.

Hard links are particularly useful when you want to reference the same file from different locations without duplicating it. However, keep in mind that hard links can only be created for files, not directories, and they must reside on the same volume.

Conclusion

Creating symbolic links, directory junctions, and hard links in PowerShell provides a robust way to manage your files and directories more efficiently. By using commands like New-Item, you can create links that streamline your workflow and reduce redundancy. Whether you’re working on a development project or organizing your files, understanding these linking techniques will enhance your productivity in Windows.

FAQ

  1. What is the difference between a symbolic link and a hard link?
    A symbolic link points to a file or directory, while a hard link points directly to the file’s data on the disk. Symbolic links can link to files or directories, but hard links can only link to files.

  2. Can I create symbolic links for directories in PowerShell?
    Yes, you can create symbolic links for both files and directories in PowerShell using the New-Item cmdlet with the -ItemType SymbolicLink parameter.

  3. Are directory junctions the same as symbolic links?
    No, directory junctions are a type of link specifically for directories and are limited to linking directories on the same volume.

  1. Can hard links be created for directories?
    No, hard links can only be created for files, not directories.

  2. How can I verify if a symbolic link was created successfully?
    You can navigate to the location of the symbolic link and check its properties or use the Get-Item cmdlet in PowerShell to verify its existence.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Приложения для 3д моделирования на windows
  • Как исправить мерцание монитора на компьютере windows 10
  • Как поменять язык на windows 7 на ноутбуке
  • Как закрыть приложение если оно не закрывается windows 10
  • Get genuine windows agreement