windowspowershellrecursion

Cannot recursively remove certain files with Remove-Item -Recurse -Force


On powershell 5.1
Using this within a foreach loop, ex:

foreach ($i in $folder.subfolders) {
   if( $i.path -like "*node_modules" ){
      Remove-Item $i.path -Force -Recurse
   }
}

I keep running into this particular error:

    + CategoryInfo          : WriteError: (_node_modules_r...dationpath.html:FileInfo) [Remove-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Remove-Item : Cannot remove item C:\topDir\js\node_modules\ram
l-1-parser\documentation\interfaces\_node_modules_raml_definition_system_node_modules_raml_typesystem_dist_src_index_d_.numbertype.html:
Could not find a part of the path '_node_modules_raml_definition_system_node_modules_raml_typesystem_dist_src_index_d_.numbertype.html'.
At C:\topDir\re.ps1:12 char:11
+           Remove-Item $i.path -Force -Recurse

The files causing the error all exist and I've checked the path and as far as my eyes can tell, they're correct?
Only thing I can make out is that the filenames are abnormally long. But surely that can't be the cause of this?


Solution

  • Long UNC names are problematic to delete. This is a OS specific thing, that limit is 260 characters.

    https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

    On Windows 10 you can enable long path names, but that does not work in all situations. I some cases you have to result to using the short name, and this requires some conversion effort.

    And ditto with what 'Beacon Bits' states, because there is no .subfolder property or method. You can see this by doing...

    (gci D:\Temp) | Get-Member | Select Name,MemberType

    If you are after the file in a parent or subfolder, you use the...

    FullName                        Property
    

    Something like...

    (gci 'D:\Temp\*.txt' -Recurse).FullName
    
    Results
    
    D:\Temp\diff\TestFile_2.txt
    ...
    D:\Temp\Duplicates\BeforeRename1\FsConfig.txt
    ...
    D:\Temp\Duplicates\dup5\SomeRandomThing.txt
    ...