PowerShell 1.0可以创建类似Unix的硬链接和软链接吗?

如果这不是内置的,有人能告诉我一个网站,有一个ps1脚本模仿这个吗?

恕我直言,这是任何优秀shell的必要功能。:)


当前回答

在Windows 7下,命令为

fsutil hardlink create new-file existing-file

PowerShell发现它没有完整的路径(c:\Windows\system32)或扩展名(.exe)。

其他回答

我发现这是一种无需外界帮助的简单方法。是的,它使用了一个古老的DOS命令,但它很有效,很简单,很清楚。

$target = cmd /c dir /a:l | ? { $_ -match "mySymLink \[.*\]$" } | % `
{
    $_.Split([char[]] @( '[', ']' ), [StringSplitOptions]::RemoveEmptyEntries)[1]
}

它使用DOS dir命令来查找带有符号链接属性的所有条目,过滤目标“[]”括号后面的特定链接名称,并且对于每个条目(假设只有一个)只提取目标字符串。

我结合了两个答案(@bviktor和@jocassid)。它在Windows 10和Windows Server 2012上进行了测试。

function New-SymLink ($link, $target)
{
    if ($PSVersionTable.PSVersion.Major -ge 5)
    {
        New-Item -Path $link -ItemType SymbolicLink -Value $target
    }
    else
    {
        $command = "cmd /c mklink /d"
        invoke-expression "$command ""$link"" ""$target"""
    }
}

你可以在PowerShell中调用cmd提供的mklink命令来创建符号链接:

cmd /c mklink c:\path\to\symlink c:\target\file

如果目标是目录,则必须将/d传递给mklink。

cmd /c mklink /d c:\path\to\symlink c:\target\directory

对于硬链接,我建议使用Sysinternals Junction之类的东西。

我写了一个PowerShell模块,它有MKLINK的本机包装器。https://gist.github.com/2891103

包括以下函数:

New-Symlink New-HardLink New-Junction

捕获MKLINK输出并在必要时抛出适当的PowerShell错误。

Windows 10(以及Powershell 5.0)允许您通过New-Item cmdlet创建符号链接。

用法:

New-Item -Path C:\LinkDir -ItemType SymbolicLink -Value F:\RealDir

或者在你的个人资料中:

function make-link ($target, $link) {
    New-Item -Path $link -ItemType SymbolicLink -Value $target
}

打开开发人员模式,在新建项目链接时不需要管理员权限: