PowerShell/Scripts/check-symlinks.ps1

55 lines
1.7 KiB
PowerShell
Raw Normal View History

2021-09-27 10:38:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2022-05-30 10:22:51 +02:00
Checks symlinks in a folder
2021-07-13 21:10:02 +02:00
.DESCRIPTION
2022-05-30 10:22:51 +02:00
This PowerShell script checks every symbolic link in a folder (including subfolders).
2022-04-27 13:30:13 +02:00
It returns the number of broken symlinks as exit value.
2021-10-16 16:50:10 +02:00
.PARAMETER folder
2022-04-27 13:30:13 +02:00
Specifies the path to the folder
2021-07-13 21:10:02 +02:00
.EXAMPLE
2022-05-30 10:22:51 +02:00
PS> ./check-symlinks C:\Users
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
2022-04-27 13:30:13 +02:00
Author: Markus Fleschutz | License: CC0
2021-02-10 16:49:09 +01:00
#>
2022-05-30 10:22:51 +02:00
param([string]$Folder = "")
2021-02-10 16:49:09 +01:00
2021-02-18 20:17:55 +01:00
try {
2022-05-30 10:22:51 +02:00
if ($Folder -eq "" ) { $Folder = read-host "Enter the path to the folder" }
2021-09-12 21:33:46 +02:00
2022-03-28 13:26:23 +02:00
$StopWatch = [system.diagnostics.stopwatch]::startNew()
2022-05-30 10:22:51 +02:00
$FullPath = Resolve-Path "$Folder"
"⏳ Checking symlinks at 📂$FullPath including subfolders..."
2022-03-28 13:26:23 +02:00
2021-09-12 21:33:46 +02:00
[int]$NumTotal = [int]$NumBroken = 0
2021-10-01 13:03:02 +02:00
Get-ChildItem $FullPath -recurse | Where { $_.Attributes -match "ReparsePoint" } | ForEach-Object {
2021-02-10 16:49:09 +01:00
$Symlink = $_.FullName
$Target = ($_ | Select-Object -ExpandProperty Target -ErrorAction Ignore)
if ($Target) {
$path = $_.FullName + "\..\" + ($_ | Select-Object -ExpandProperty Target)
$item = Get-Item $path -ErrorAction Ignore
if (!$item) {
2021-09-12 21:33:46 +02:00
$NumBroken++
2022-05-30 10:22:51 +02:00
"Broken symlink #$($NumBroken): $Symlink$Target"
2021-02-10 16:49:09 +01:00
}
}
2021-09-12 21:33:46 +02:00
$NumTotal++
2021-02-10 16:49:09 +01:00
}
2021-08-24 20:46:03 +02:00
2022-03-28 13:26:23 +02:00
[int]$Elapsed = $StopWatch.Elapsed.TotalSeconds
2022-04-27 13:30:13 +02:00
if ($NumTotal -eq 0) {
"✔️ found no symlink at 📂$FullPath in $Elapsed sec"
} elseif ($NumBroken -eq 0) {
"✔️ found $NumTotal valid symlinks at 📂$FullPath in $Elapsed sec"
2022-05-30 10:22:51 +02:00
} elseif ($NumBroken -eq 1) {
"✔️ found $NumBroken broken symlink out of $NumTotal at 📂$FullPath in $Elapsed sec"
2022-04-27 13:30:13 +02:00
} else {
2022-05-30 10:22:51 +02:00
"✔️ found $NumBroken broken symlinks out of $NumTotal at 📂$FullPath in $Elapsed sec"
2022-04-27 13:30:13 +02:00
}
2021-09-12 21:37:31 +02:00
exit $NumBroken
2021-02-10 16:49:09 +01:00
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2021-02-10 16:49:09 +01:00
exit 1
2022-05-30 08:12:48 +02:00
}