前言

更适合Powershell体质的grep中重定义了grep。Linux中的ln命令也非常好用,创建软链接,可以省下很多需要复用的文件空间。

没想到Powershell中没办法使用cmd的mklink,自带的创建软连接命令比我命还长。自己写一个脚本重定向!

代码

因为不能执行cmd命令,只能使用Powershell函数,因此新建一个ln.psm1模块,并保存到C:\Users\UserName\Documents\PowerShell\Modules\ln,在Powershell初始化时导入即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function ln {

param(
[switch]$d, # -d: 强制目录链接
[switch]$h, # -h: 显示帮助
[string]$target,
[string]$link
)

# ======== 彩色帮助 ========
if ($h -or -not $target -or -not $link) {

Write-Host "" # 空行

Write-Host "ln: create symbolic link " -ForegroundColor Cyan -NoNewline
Write-Host "(PowerShell version)" -ForegroundColor DarkGray

Write-Host ""
Write-Host "Usage:" -ForegroundColor Yellow
Write-Host " ln [-d] <target> <link>" -ForegroundColor White

Write-Host ""
Write-Host "Options:" -ForegroundColor Yellow
Write-Host " -d create directory symbolic link" -ForegroundColor White
Write-Host " -h display this help" -ForegroundColor White

Write-Host ""
Write-Host "Examples:" -ForegroundColor Yellow
Write-Host " ln C:\real\file.txt C:\link\file.txt" -ForegroundColor Green
Write-Host " ln C:\realDir C:\linkDir" -ForegroundColor Green
Write-Host " ln -d C:\realDir C:\linkDir" -ForegroundColor Green

Write-Host ""
return
}

# ======== 参数检查 ========
if (-not (Test-Path $target)) {
Write-Host "ln: target '$target' not found" -ForegroundColor Red
return
}

# ======== 设置类型(SymbolicLink)========
$itemType = "SymbolicLink"

# ======== 创建符号链接 ========
try {
New-Item -ItemType $itemType -Path $link -Target $target | Out-Null
Write-Host "ln: created symbolic link " -ForegroundColor Cyan -NoNewline
Write-Host "'$link'" -ForegroundColor Green -NoNewline
Write-Host " → " -ForegroundColor DarkGray -NoNewline
Write-Host "'$target'" -ForegroundColor Green
}
catch {
Write-Host "ln: failed to create link: $($_.Exception.Message)" -ForegroundColor Red
}
}

然后在Powershell里执行$PROFILE即可看到配置文件位置,一般在C:\Users\UserName\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

在末尾加上Import-Module ln即可。