-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-SymbolicLink.ps1
More file actions
437 lines (386 loc) · 16.2 KB
/
Copy pathRemove-SymbolicLink.ps1
File metadata and controls
437 lines (386 loc) · 16.2 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
function Remove-SymbolicLink
{
<#
.SYNOPSIS
Removes a symbolic link without deleting the target.
.DESCRIPTION
Safely removes a symbolic link (symlink) at the specified path without affecting the
target file or directory that it points to. This function is cross-platform compatible
and works on Windows, macOS, and Linux.
The function validates that the specified path is actually a symbolic link before
attempting removal, preventing accidental deletion of regular files or directories.
.PARAMETER Path
The path to the symbolic link to remove. This must be an existing symbolic link.
Supports relative paths and tilde (~) expansion.
Accepts pipeline input and can process multiple paths.
.PARAMETER Force
When specified, suppresses the validation that the path is a symbolic link and
removes the item regardless. Use with caution as this could delete regular files
or directories.
.PARAMETER PassThru
Returns information about the removed symbolic link including its former target.
.PARAMETER WhatIf
Shows what would happen if the cmdlet runs without actually removing the symbolic link.
.PARAMETER Confirm
Prompts for confirmation before removing the symbolic link.
.EXAMPLE
PS > Remove-SymbolicLink -Path '~/link-to-docs'
Removes the symbolic link named 'link-to-docs' from the home directory.
.EXAMPLE
PS > Remove-SymbolicLink -Path 'C:\MyLink.txt' -PassThru
Removes the symbolic link and returns information about what was removed.
.EXAMPLE
PS > Get-ChildItem -Path '~/links' | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint } | Remove-SymbolicLink
Removes all symbolic links in the ~/links directory via pipeline.
.EXAMPLE
PS > Remove-SymbolicLink -Path './config', './data', './logs' -WhatIf
Shows what would happen when removing multiple symbolic links.
.EXAMPLE
PS > 'link1', 'link2', 'link3' | Remove-SymbolicLink -Confirm
Removes multiple symbolic links with confirmation prompts for each.
.OUTPUTS
None by default.
[PSCustomObject] when -PassThru is specified, containing:
- Path: The path of the removed symbolic link
- Target: The target the symbolic link pointed to
- ItemType: Whether it was a file or directory symbolic link
- Removed: Boolean indicating successful removal
.NOTES
Symbolic Link Detection:
- On all platforms, symbolic links have the ReparsePoint attribute
- The function checks this attribute to verify the path is a symbolic link
- Use -Force to bypass this check (not recommended)
Safety Features:
- Validates the path exists before attempting removal
- Validates the path is a symbolic link (unless -Force is used)
- Does not follow the symbolic link or affect the target
- Supports -WhatIf and -Confirm for safe operation
Cross-Platform Behavior:
- Windows: Uses Remove-Item which properly handles reparse points
- macOS/Linux: Uses Remove-Item which properly handles symbolic links
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Remove-SymbolicLink.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Utilities/Remove-SymbolicLink.ps1
.LINK
New-SymbolicLink
.LINK
https://learn.microsoft.com/powershell/module/microsoft.powershell.management/remove-item
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([System.Object[]])]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('FullName', 'LiteralPath')]
[String[]]$Path,
[Parameter()]
[Switch]$Force,
[Parameter()]
[Switch]$PassThru
)
begin
{
Write-Verbose 'Starting symbolic link removal'
$results = [System.Collections.ArrayList]::new()
function Test-ResolvedItemExists
{
param([String]$LiteralPath)
if (Test-Path -LiteralPath $LiteralPath)
{
return $true
}
try
{
[void][System.IO.File]::GetAttributes($LiteralPath)
return $true
}
catch
{
return $false
}
}
}
process
{
foreach ($symlinkPath in $Path)
{
try
{
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($symlinkPath)
}
catch
{
Write-Error "Failed to resolve path '$symlinkPath': $($_.Exception.Message)"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $symlinkPath
Target = $null
ItemType = $null
Removed = $false
Error = $_.Exception.Message
}
$null = $results.Add($result)
}
continue
}
Write-Verbose "Processing symbolic link: $resolvedPath"
# Check if the path exists
if (-not (Test-ResolvedItemExists -LiteralPath $resolvedPath))
{
Write-Error "Path not found: $resolvedPath"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $null
ItemType = $null
Removed = $false
Error = 'Path not found'
}
$null = $results.Add($result)
}
continue
}
# Get the item to check if it's a symbolic link
# Note: On Windows PowerShell 5.1, Get-Item can have issues with directory symbolic links
# where $item.Attributes may be null, causing NullReferenceException when checking attributes.
# We use [System.IO.File]::GetAttributes() as a more reliable alternative.
$item = $null
$itemAttributes = $null
try
{
$item = Get-Item -LiteralPath $resolvedPath -Force -ErrorAction Stop
# Try to get attributes via .NET for more reliable detection on PS 5.1
$itemAttributes = [System.IO.File]::GetAttributes($resolvedPath)
}
catch
{
# If Get-Item fails but path exists, try .NET approach for attributes
if (Test-ResolvedItemExists -LiteralPath $resolvedPath)
{
try
{
$itemAttributes = [System.IO.File]::GetAttributes($resolvedPath)
}
catch
{
Write-Error "Failed to access item at '$resolvedPath': $($_.Exception.Message)"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $null
ItemType = $null
Removed = $false
Error = $_.Exception.Message
}
$null = $results.Add($result)
}
continue
}
}
else
{
Write-Error "Failed to access item at '$resolvedPath': $($_.Exception.Message)"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $null
ItemType = $null
Removed = $false
Error = $_.Exception.Message
}
$null = $results.Add($result)
}
continue
}
}
# Check if it's a symbolic link (ReparsePoint attribute)
# Use .NET attributes for reliable detection, especially on Windows PowerShell 5.1
$isSymbolicLink = $false
if ($null -ne $itemAttributes)
{
$isSymbolicLink = $itemAttributes -band [System.IO.FileAttributes]::ReparsePoint
}
elseif ($null -ne $item -and $null -ne $item.Attributes)
{
$isSymbolicLink = $item.Attributes -band [System.IO.FileAttributes]::ReparsePoint
}
if (-not $isSymbolicLink -and -not $Force)
{
# Determine item type for error reporting
$errorItemType = 'File'
if ($null -ne $item -and $item.PSIsContainer)
{
$errorItemType = 'Directory'
}
elseif ($null -ne $itemAttributes -and ($itemAttributes -band [System.IO.FileAttributes]::Directory))
{
$errorItemType = 'Directory'
}
Write-Error "Path is not a symbolic link: $resolvedPath. Use -Force to remove anyway (not recommended)."
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $null
ItemType = $errorItemType
Removed = $false
Error = 'Not a symbolic link'
}
$null = $results.Add($result)
}
continue
}
# Get the target of the symbolic link for reporting
$linkTarget = $null
# Determine item type - check $item first, fall back to .NET attributes
$itemType = 'File'
if ($null -ne $item -and $item.PSIsContainer)
{
$itemType = 'Directory'
}
elseif ($null -ne $itemAttributes -and ($itemAttributes -band [System.IO.FileAttributes]::Directory))
{
$itemType = 'Directory'
}
if ($isSymbolicLink)
{
try
{
# PowerShell 6+ has LinkTarget property, PowerShell 5.1 needs different approach
if ($PSVersionTable.PSVersion.Major -ge 6)
{
$linkTarget = $item.LinkTarget
}
else
{
# For PowerShell 5.1 on Windows, use Target property if available
if ($item.Target)
{
$linkTarget = $item.Target
}
}
}
catch
{
Write-Verbose "Could not determine symbolic link target: $($_.Exception.Message)"
}
}
# Remove the symbolic link
$actionDescription = if ($isSymbolicLink)
{
"Remove symbolic link (target: $linkTarget)"
}
else
{
'Remove item (Force mode - not a symbolic link)'
}
if ($PSCmdlet.ShouldProcess($resolvedPath, $actionDescription))
{
try
{
# Remove the symbolic link
# Note: Directory symlinks on Windows PowerShell 5.1 can be problematic with Remove-Item.
# We use a multi-tier approach for reliable removal:
# 1. Try [System.IO.Directory]::Delete() for directory symlinks (most reliable on PS 5.1)
# 2. Fall back to cmd.exe rmdir for directory symlinks on Windows
# 3. Use Remove-Item as last resort
$removed = $false
$isDirectory = $itemType -eq 'Directory'
if ($isDirectory -and $PSVersionTable.PSVersion.Major -lt 6)
{
# Windows PowerShell 5.1 - use .NET method for directory symlinks
try
{
[System.IO.Directory]::Delete($resolvedPath)
$removed = $true
Write-Verbose "Removed directory symlink using .NET method: $resolvedPath"
}
catch
{
Write-Verbose ".NET Directory.Delete failed: $($_.Exception.Message). Trying cmd.exe rmdir..."
# Try cmd.exe rmdir as fallback for Windows
try
{
$null = cmd.exe /c "rmdir `"$resolvedPath`"" 2>&1
if (-not (Test-ResolvedItemExists -LiteralPath $resolvedPath))
{
$removed = $true
Write-Verbose "Removed directory symlink using cmd.exe rmdir: $resolvedPath"
}
}
catch
{
Write-Verbose "cmd.exe rmdir failed: $($_.Exception.Message)"
}
}
}
# If not removed yet, use standard Remove-Item
if (-not $removed)
{
# IMPORTANT: Do NOT use -Recurse on symbolic links, especially on Windows PowerShell 5.1.
# Using -Recurse on a directory symlink attempts to recurse into the target directory,
# which can fail or delete target contents. We only remove the symlink itself.
Remove-Item -LiteralPath $resolvedPath -Force -ErrorAction Stop
$removed = $true
}
Write-Verbose "Successfully removed symbolic link: $resolvedPath"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $linkTarget
ItemType = $itemType
Removed = $true
Error = $null
}
$null = $results.Add($result)
}
}
catch
{
Write-Error "Failed to remove symbolic link '$resolvedPath': $($_.Exception.Message)"
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $linkTarget
ItemType = $itemType
Removed = $false
Error = $_.Exception.Message
}
$null = $results.Add($result)
}
}
}
else
{
# WhatIf mode - still add to results if PassThru
if ($PassThru)
{
$result = [PSCustomObject]@{
Path = $resolvedPath
Target = $linkTarget
ItemType = $itemType
Removed = $false
Error = 'WhatIf mode - not removed'
}
$null = $results.Add($result)
}
}
}
}
end
{
if ($PassThru)
{
return @($results)
}
Write-Verbose 'Symbolic link removal completed'
}
}