0

I am in the process of setting up a shared network drive, that gets emptied periodically.

Its purpose is to provide an easy file sharing option for the users. Since I can't enforce them to always clean up after themselves, I want this drive to get emptied periodically.

I found and tried this using command prompt:

del /q "D:\Transfer$\*"

And then this:

del /q "D:\Transfer$\*"
for /D %p IN (D:\Transfer$\*) DO rmdir "%p" /s /q

But these don't delete the folders, only files.

How would the some code look, that deletes all contents (folders and files) of a given folder, without deleting the folder itself?

5

3 Answers 3

1

Since you tagged for PowerShell even though your efforts and attempts were unsuccessful with batch/cmd—this PowerShell solution works as you prefer, and since you are considering "PowerShell" for a potential solution too.

This takes a full explicit source folder path and deletes all files and all subfolders beneath the source folder recursively—it does not delete the source folder itself, just everything within it.

PowerShell

$srcPath = "D:\Transfer$";
Get-ChildItem -Path $srcPath | ForEach-Object -Process { 
    If($_.attributes -eq "Directory"){
        Remove-Item -Path $_.FullName -Recurse -Force;
        }Else{
        Remove-Item -Path $_.FullName -Force;};
        };

Supporting Resources

1
  • 1
    Thank you for the answer, this works perfectly. User Destroy666 also suggested other questions and I found this answer, which works aswell.
    – fraenzz
    Commented Jun 2, 2023 at 8:50
2

The PowerShell solution can be simplified even further. The output of Get-ChildItem can be piped directly to Remove-Item. The -Recurse parameter ensures deletion of subdidrectories and any content within, but is simply ignored if the pipeline input is a file path:

### Single quotes ensure "$" is treated as a literal character. 
$Path = 'D:\Transfer$'

Get-ChildItem $Path | Remove-Item -Recurse -Force
1
  • 1
    This is a perfect solution, good to know!
    – Io-oI
    Commented Jun 2, 2023 at 20:29
0
$RemoveDir="D:\Transfer$"
$CurrentDir=(Get-Location).path

cd $RemoveDir -ErrorAction SilentlyContinue | Out-Null 
if ( $CurrentDir -eq $RemoveDir ) { Remove-Item -path $RemoveDir\* -Recurse }

@echo off 

cd /d "D:\Transfer$" && (
     del /f /a /q .\* 
     for /r /d %%i in (*)do RmDir /q /s "%%~fi"
    )

cd /d "D:\Transfer$" && (del /f /a /q .\* & for /r /d %i in (*)do RmDir /q /s "%~fi")
1
  • Thanks for your answer, the powershell script works, the cmd/batch script however does not.
    – fraenzz
    Commented Jun 2, 2023 at 8:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .