개발이나 시스템 관리 작업을 하다 보면 특정 이름을 가진 디렉토리들을 한 번에 찾아서 삭제해야 하는 경우가 자주 발생합니다. 예를 들어, 빌드 과정에서 생성된 temp, cache, node_modules 같은 디렉토리들이나, 백업 작업 중 생성된 임시 폴더들을 정리할 때 말이죠.
이번 포스트에서는 윈도우 환경에서 특정 이름의 디렉토리를 하위 경로까지 모두 검색해서 안전하게 삭제하는 방법을 자세히 알아보겠습니다.
1. PowerShell을 이용한 방법 (권장)
PowerShell은 강력하고 안전한 기능을 제공하므로 가장 권장하는 방법입니다.
기본 문법
Get-ChildItem -Path "검색경로" -Directory -Name "디렉토리명" -Recurse | Remove-Item -Recurse -Force
주요 옵션 설명
-Path: 검색을 시작할 경로 지정-Directory: 디렉토리만 검색 대상으로 제한-Name: 찾을 디렉토리의 정확한 이름-Recurse: 하위 디렉토리까지 재귀적으로 검색-Force: 읽기 전용이나 숨김 파일도 강제로 삭제Remove-Item -Recurse: 디렉토리와 그 안의 모든 내용을 삭제
안전한 단계별 실행
# 1단계: 삭제 대상 미리 확인
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse | Select-Object FullName
# 2단계: 확인 후 실제 삭제
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse | Remove-Item -Recurse -Force
시뮬레이션 모드 (-WhatIf)
실제 삭제 전에 어떤 작업이 수행될지 미리 확인할 수 있습니다:
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse | Remove-Item -Recurse -Force -WhatIf
2. 명령 프롬프트(CMD)를 이용한 방법
PowerShell을 사용할 수 없는 환경에서는 CMD를 활용할 수 있습니다.
디렉토리 찾기
dir /s /b /ad "C:\Projects" | findstr "temp$"
옵션 설명
/s: 하위 디렉토리까지 검색/b: 파일명만 표시 (경로 포함)/ad: 디렉토리만 표시findstr "temp$": 이름이 정확히 “temp”로 끝나는 항목만 필터링
일괄 삭제
for /f "delims=" %i in ('dir /s /b /ad "C:\Projects" ^| findstr "\\temp$"') do rmdir /s /q "%i"
배치 파일(.bat)에서 사용할 때는 %i를 %%i로 변경해야 합니다.
3. 실용적인 사용 예시
개발 환경 정리
# node_modules 디렉토리 모두 삭제
Get-ChildItem -Path "C:\Development" -Directory -Name "node_modules" -Recurse | Remove-Item -Recurse -Force
# 빌드 결과물 정리
Get-ChildItem -Path "C:\Projects" -Directory -Name "bin" -Recurse | Remove-Item -Recurse -Force
Get-ChildItem -Path "C:\Projects" -Directory -Name "obj" -Recurse | Remove-Item -Recurse -Force
임시 파일 정리
# 다양한 임시 디렉토리 한 번에 정리
$tempDirs = @("temp", "tmp", "cache", ".cache")
foreach ($dir in $tempDirs) {
Get-ChildItem -Path "C:\Users\$env:USERNAME" -Directory -Name $dir -Recurse | Remove-Item -Recurse -Force
}
백업 디렉토리 정리
# 날짜 패턴이 포함된 백업 디렉토리 찾기
Get-ChildItem -Path "C:\Backups" -Directory | Where-Object { $_.Name -match "backup_\d{8}" } | Remove-Item -Recurse -Force
4. 고급 활용법
조건부 삭제
특정 조건을 만족하는 디렉토리만 삭제할 수 있습니다:
# 30일 이상 된 temp 디렉토리만 삭제
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
Remove-Item -Recurse -Force
크기 기준 삭제
# 100MB 이상인 cache 디렉토리만 삭제
Get-ChildItem -Path "C:\Projects" -Directory -Name "cache" -Recurse |
Where-Object { (Get-ChildItem $_.FullName -Recurse | Measure-Object -Property Length -Sum).Sum -gt 100MB } |
Remove-Item -Recurse -Force
로그 기록과 함께 삭제
# 삭제 작업을 로그 파일에 기록
$logFile = "C:\Logs\cleanup_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse |
ForEach-Object {
"삭제: $($_.FullName) - $(Get-Date)" | Add-Content $logFile
Remove-Item $_.FullName -Recurse -Force
}
5. 유용한 추가 명령어
디렉토리 검색만 하기
# 검색 결과를 표 형태로 보기
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse |
Select-Object Name, FullName, LastWriteTime | Format-Table -AutoSize
# 검색 결과를 CSV로 내보내기
Get-ChildItem -Path "C:\Projects" -Directory -Name "temp" -Recurse |
Select-Object Name, FullName, LastWriteTime | Export-Csv -Path "temp_directories.csv" -NoTypeInformation
여러 디렉토리 이름 동시 검색
# 여러 패턴 동시 검색
$patterns = @("temp", "cache", "tmp", ".git")
foreach ($pattern in $patterns) {
Write-Host "검색 중: $pattern"
Get-ChildItem -Path "C:\Projects" -Directory -Name $pattern -Recurse |
Select-Object FullName
}
정규식을 이용한 고급 검색
# 특정 패턴에 맞는 디렉토리 찾기
Get-ChildItem -Path "C:\Projects" -Directory -Recurse |
Where-Object { $_.Name -match "^(temp|cache|tmp)_\d+$" } |
Remove-Item -Recurse -Force
6. 주의사항 및 모범 사례
안전 수칙
- 항상 백업부터: 중요한 데이터가 있을 수 있으니 전체 백업을 먼저 수행하세요
- 테스트 실행:
-WhatIf옵션이나 검색만 먼저 실행해서 대상을 확인하세요 - 권한 확인: 관리자 권한이 필요한 경우가 있으니 PowerShell을 관리자로 실행하세요
- 경로 검증: 타이핑 실수로 잘못된 경로를 지정하지 않도록 주의하세요
성능 최적화
# 대용량 디렉토리 처리 시 진행 상황 표시
$dirs = Get-ChildItem -Path "C:\Projects" -Directory -Name "node_modules" -Recurse
$total = $dirs.Count
$current = 0
foreach ($dir in $dirs) {
$current++
Write-Progress -Activity "디렉토리 삭제 중" -Status "$current/$total" -PercentComplete (($current/$total)*100)
Remove-Item $dir.FullName -Recurse -Force
}
스크립트 파일로 저장
자주 사용하는 정리 작업은 스크립트 파일로 저장해두면 편리합니다:
# cleanup_temp.ps1
param(
[Parameter(Mandatory=$true)]
[string]$BasePath,
[string[]]$DirectoryNames = @("temp", "cache", "tmp"),
[switch]$WhatIf
)
foreach ($dirName in $DirectoryNames) {
Write-Host "처리 중: $dirName" -ForegroundColor Green
if ($WhatIf) {
Get-ChildItem -Path $BasePath -Directory -Name $dirName -Recurse |
Select-Object FullName
} else {
Get-ChildItem -Path $BasePath -Directory -Name $dirName -Recurse |
Remove-Item -Recurse -Force
}
}
사용법:
# 시뮬레이션
.\cleanup_temp.ps1 -BasePath "C:\Projects" -WhatIf
# 실제 실행
.\cleanup_temp.ps1 -BasePath "C:\Projects"
마무리
특정 디렉토리를 일괄 삭제하는 작업은 시스템 관리나 개발 환경 정리에서 매우 유용한 기능입니다. PowerShell의 강력한 기능을 활용하면 안전하고 효율적으로 작업을 수행할 수 있습니다.
가장 중요한 것은 안전입니다. 항상 백업을 먼저 하고, 테스트 실행으로 대상을 확인한 후 실제 삭제를 진행하시기 바랍니다. 이러한 도구들을 현명하게 활용해서 반복적인 작업을 자동화하고 생산성을 높여보세요!