Delete broken link

2019-09-07 02:17发布

I need to delete all the content of a folder which may include broken links among others. The folder path is provided by a variable. Problem is that PowerShell fails to remove the broken links.

$folderPath = "C:\folder\"

Attempt 1:

Remove-Item -Force -Recurse -Path $folderPath

Fails with error:

Remove-Item : Could not find a part of the path 'C:\folder\brokenLink'.
At line:1 char:1
+ Remove-Item -Force -Recurse -Path $folderPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\folder\brokenLink:String) [Remove-Item], DirectoryNot 
   FoundException
    + FullyQualifiedErrorId : RemoveItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

Attempt 2:

Start-Job { cmd /c rmdir $folderPath }

Fails because $folderPath gets passed as is instead of its value:

Start-Job { cmd /c rmdir $folderPath } | select command

Command                                                                                             
-------                                                                                             
 cmd /c rmdir $folderPath                                                                           

Any suggestion besides using the .NET framework?

EDIT
By broken link I'm referring to a folder which points to a previously mounted partition, that doesn't exist anymore. The folder is still available but when attempting to navigate into it this error occurs because the destination doesn't exist anymore:
Error:

C:\folder\brokenLink refers to a location that is unavailable. It could be on a hard drive on this computer, or on a network. Check to make sure that the disk is properly inserted, or that you are connected to the Internet or your network, and then try again. If it still cannot be located, the information might have been moved to a different location.

1条回答
可以哭但决不认输i
2楼-- · 2019-09-07 02:36

This will work:

$folderPath = "C:\folderContaingBrokenSymlinks\";
$items = ls $folderPath -Recurse -ea 0;
foreach($item in $items){
    if($item.Attributes.ToString().contains("ReparsePoint")){
        cmd /c rmdir $item.PSPath.replace("Microsoft.PowerShell.Core\FileSystem::","");
    }
    else{
        rm -Force -Recurse $item;
    }
}
查看更多
登录 后发表回答