Reputation: 2053
As of Windows 10 PowerShell is finally capable of creating Junctions and links natively.
Howerver the Remove-Item function seems to be unaware of the junction and tries to remove the directory asking for confirmation and if it should recursively delete items within.
So, the question is: Is there a way to remove a junction using PowerShell native Cmdlets? (i.e. without calling cmd)
Upvotes: 15
Views: 22365
Reputation: 16940
Be careful with removing junctions.
# Check by only showing junction links:
(Get-ChildItem . -Force -Recurse | Where-Object { $_.LinkType -eq "Junction" -and $_.Attributes -match "ReparsePoint" }) | Select FullName, LinkType, Target
# WARNING: This recursively remove all junction links
(Get-ChildItem . -Force -Recurse | Where-Object { $_.LinkType -eq "Junction" -and $_.Attributes -match "ReparsePoint" }) | Select $_.FullName | Remove-Item -Force -Recurse
Upvotes: 1
Reputation: 330
I know this post is old, but for anyone looking into this in 2023, you can use the following PS cmdlet-combination to remove a junction but not its contents :
$junction = Get-Item -Path <path_to_junction>
$junction.Delete()
That path is the actual junction path, not the parent path.
This can be condensed to :
(gi <path>).Delete()
Upvotes: 3
Reputation: 11
After search by Google for a long time, I found the answer:
function Remove-Any-File-Force ($Target) {
if ( Test-Path -Path "$Target" ){
& $env:SystemRoot\System32\ATTRIB.exe -S -H -R "$Target" >$null 2>$null
} else {
return
}
$TargetAttributes = (Get-Item -Path $Target -Force).Attributes.ToString()
if ($TargetAttributes -match "ReparsePoint") {
if ($TargetAttributes -match "Archive") {
Remove-Item -Path "$Target" -Force
} else {
try {
& $env:SystemRoot\System32\cmd.exe /c rmdir /Q "$Target" >$null 2>$null
} catch {
try {
[io.directory]::Delete("$Target")
} catch {
Remove-Item -Path "$Target" -Force
}
}
}
} else {
if ($TargetAttributes -match "Directory") {
Remove-Item -Path "$Target" -Force -Recurse
} else {
Remove-Item -Path "$Target" -Force
}
}
}
Upvotes: 0
Reputation: 46710
Is there a way to remove a junction using PowerShell?
Currently, at least in PowerShell v5, this is considered "fixed". What you can do is use the -Force
switch, else you will get an error calling the path an NTFS junction. The reason that I at least use the quotes on fixed is that using the switch will still make the message about children in the directory show up. Selecting Y will still only delete the junction in my testing using PSv5.
Remove-Item "C:\temp\junction" -Force -Confirm:$False
If that doesn't work for you or you don't have v5 you can use the .Net method to delete a directory. This appears to work correctly as well.
[io.directory]::Delete("C:\temp\junction")
Upvotes: 14
Reputation: 1335
have a try on this "command-let":
cmd /c rmdir .\Target
source:Powershell Remove-Item and symbolic links
Upvotes: 2