Remove node_modules Folders Recursively

Code Properties

  • Language: PowerShell
  • Cmdlets: Get-ChildItem, Remove-Item

Overview

Sources:

PowerShell command to recursively find and remove all node_modules folders in a directory tree, useful for freeing disk space and avoiding path length issues.

Code

# note: eliminate -WhatIf parameter to actually perform the deletion
# note: PowerShell versions prior to 4.0 cannot delete non-empty folders
 
Get-ChildItem -Path "." -Include "node_modules" -Recurse -Directory | Remove-Item -Recurse -Force -WhatIf

Usage

# preview what will be deleted (dry run)
Get-ChildItem -Path "C:\Projects" -Include "node_modules" -Recurse -Directory | Remove-Item -Recurse -Force -WhatIf
 
# actually delete all node_modules folders
Get-ChildItem -Path "C:\Projects" -Include "node_modules" -Recurse -Directory | Remove-Item -Recurse -Force
 
# with confirmation for each folder
Get-ChildItem -Path "." -Include "node_modules" -Recurse -Directory | Remove-Item -Recurse -Force -Confirm

Appendix

Note created on 2024-05-03 and last modified on 2024-12-31.

See Also


(c) No Clocks, LLC | 2024