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?

fraenzz
  • 123
  • 1
  • 5

3 Answers3

3

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

Io-oI
  • 9,237
Keith Miller
  • 10,694
  • 1
  • 20
  • 35
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

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")
Io-oI
  • 9,237