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

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

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


当前回答

New-Symlink:

Function New-SymLink ($link, $target)
{
    if (test-path -pathtype container $target)
    {
        $command = "cmd /c mklink /d"
    }
    else
    {
        $command = "cmd /c mklink"
    }

    invoke-expression "$command $link $target"
}

Remove-Symlink:

Function Remove-SymLink ($link)
{
    if (test-path -pathtype container $link)
    {
        $command = "cmd /c rmdir"
    }
    else
    {
        $command = "cmd /c del"
    }

    invoke-expression "$command $link"
}

用法:

New-Symlink "c:\foo\bar" "c:\foo\baz"
Remove-Symlink "c:\foo\bar"

其他回答

你可以在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之类的东西。

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

尝试junction.exe

来自SysInternals的Junction命令行实用程序可以轻松地创建和删除连接。

进一步的阅读

MS术语:软!=符号 微软使用“软链接”作为“连接”的另一个名称。 然而,“符号链接”完全是另一回事。 参见MSDN: Windows中的硬链接和连接。 (这与“软链接”和“符号链接”(“symlink”)的一般用法完全相反。)