Let’s say you’ve got a symbolic link which points to another folder and you want to delete the symbolic link through Powershell. Prepare for some weird stuff! Consider the following test script:
New-Item "SymbolicTest" -Type Directory Set-Location "SymbolicTest" New-Item "Source" -Type Directory Set-Location "Source" New-Item "Test1.txt" -Type File New-Item "Test2.txt" -Type File New-Item "Test3.txt" -Type File Set-Location "../" # now some cmd since Powershell can't natively create symbolic links cmd /c mklink /J `"Target`" `"Source`" ls
Let’s check the structure: Okay, so no difference, both are considered directories. Now let’s check with cmd: Okay, weird, cmd understands it. Now let’s try to remove the Target link. Remember, we only want to delete the link, not the contents of the Target folder (and thus implicitly not the contents of the Source folder). With Remove-Item you can delete items. Let’s try it out:
This yields the following output:
Wait what? Deletion of the children. Just for the sake of it I typed Y. This yielded another error: Okay, again, with -Force Target was gone, however also the contents of Source. Auch? Now what? Well, reading through the documentation of Remove-Item I found nothing about symbolic links.
So what now? Seems that Powershell doesn’t have knowledge about symbolic links. It wasn’t taken into account. He just follows the link like it’s a normal directory.
So what’s the solution? I decided to use the good old cmd (from Powershell!):
cmd /c rmdir .\Target
Marvelous. Problem solved!
Actually, in retrospect, since I needed to use cmd to create the link, it would have made more sense to also just delete the link with cmd!
Have a good one,