Created
April 29, 2025 16:10
-
-
Save ShadowPower/f65b3e9415f6d48b193540d176796e34 to your computer and use it in GitHub Desktop.
批量创建符号链接,并删除失效的符号链接
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
[Parameter(Mandatory=$true)] | |
[string]$SourceDir, | |
[Parameter(Mandatory=$true)] | |
[string]$TargetDir | |
) | |
# 验证源目录是否存在 | |
if (-not (Test-Path -Path $SourceDir -PathType Container)) { | |
Write-Error "源目录不存在: $SourceDir" | |
exit 1 | |
} | |
# 创建目标目录(如果不存在) | |
if (-not (Test-Path -Path $TargetDir -PathType Container)) { | |
New-Item -ItemType Directory -Path $TargetDir -Force | Out-Null | |
} | |
# 删除无效符号链接的函数 | |
function Remove-InvalidSymlinks { | |
param($Path) | |
Get-ChildItem -Path $Path | ForEach-Object { | |
$item = $_ | |
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { | |
try { | |
$target = $item.Target | |
if (-not $target) { | |
Remove-Item -Path $item.FullName -Force | |
Write-Host "已删除无效符号链接: $($item.FullName)" | |
return | |
} | |
$resolvedTarget = if ([IO.Path]::IsPathRooted($target)) { | |
$target | |
} else { | |
Join-Path -Path $item.Directory.FullName -ChildPath $target | |
} | |
if (-not (Test-Path -Path $resolvedTarget)) { | |
Remove-Item -Path $item.FullName -Force | |
Write-Host "已删除无效符号链接: $($item.FullName)" | |
} | |
} catch { | |
Write-Host "处理项目时出错: $($item.FullName)" | |
} | |
} | |
} | |
} | |
# 清理目标目录中的无效符号链接 | |
Remove-InvalidSymlinks -Path $TargetDir | |
# 创建符号链接 | |
Get-ChildItem -Path $SourceDir -File | ForEach-Object { | |
$sourceFile = $_ | |
$targetPath = Join-Path -Path $TargetDir -ChildPath $sourceFile.Name | |
if (Test-Path -Path $targetPath) { | |
$targetItem = Get-Item -Path $targetPath -Force -ErrorAction SilentlyContinue | |
if ($targetItem) { | |
if ($targetItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { | |
Write-Host "已存在符号链接,跳过: $targetPath" | |
return | |
} | |
Write-Host "目标存在但非符号链接,跳过: $targetPath" | |
return | |
} | |
} | |
try { | |
$null = New-Item -ItemType SymbolicLink -Path $targetPath -Target $sourceFile.FullName -Force -ErrorAction Stop | |
Write-Host "已创建符号链接: $targetPath -> $($sourceFile.FullName)" | |
} | |
catch { | |
if ($_.Exception.Message -match "A required privilege is not held by the client") { | |
Write-Error "需要管理员权限创建符号链接!请以管理员身份运行PowerShell" | |
exit 1 | |
} | |
Write-Error "创建符号链接失败: $targetPath. 错误: $_" | |
} | |
} | |
Write-Host "操作完成" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment