Advertisement
0utsidethebox

PowerShell with ChatGPT: delete folders matching archive names

Oct 29th, 2023 (edited)
1,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <# There is a folder c:\test that contains multiple files and folders. Create powershell code that deletes only the folders with names that match rar archives located in the same folder c:\test #>
  2.  
  3. $folderPath = "C:\test"
  4. $rarFiles = Get-ChildItem -Path $folderPath -Filter "*.rar" -File
  5.  
  6. foreach ($rarFile in $rarFiles) {
  7.     $folderName = $rarFile.BaseName
  8.     $folderToDelete = Join-Path -Path $folderPath -ChildPath $folderName
  9.  
  10.     if (Test-Path -Path $folderToDelete -PathType Container) {
  11.         Remove-Item -Path $folderToDelete -Recurse -Force
  12.         Write-Host "Deleted folder: $folderToDelete"
  13.     }
  14. }
  15.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement