Script to delete folders and subfolders from a specific folder full of subfolders

windows-server-2012

I have a folder (Users) full of user folders that we use for temporary transfer between users. I want to be able schedule a script to empty the contents of the users folders without removing the user folders or changing permissions.

Is there a way to do this via a batch file? I thought originally I could use something like:

del /F \Users**.*

But that didn't work.

Please help!

And Thank you!!

Best Answer

You're on Server 2012... you have about 0 reason to use batch.

Here, have some Powershell:

Foreach($_ In Get-ChildItem C:\Users -Recurse) 
{ 
    If(!$_.PSIsContainer) { Remove-Item $_.Fullname } 
}

That will delete all files in and under the C:\Users directory tree, but it will leave all the directories intact.

Edit:

How about this:

Foreach($_ In Get-ChildItem C:\Users)
{
    If($_.PSIsContainer)
    {
        Get-ChildItem $_.FullName -Recurse | Remove-Item
    }   
}

So now what we're doing is getting a list of "first-level" directories under C:\Users, and then recursively clearing out the contents of each of those folders, so in the end the only things that will be left are C:\Users and the first level of subdirectories under it.

Edit: Since you mentioned that you would like to understand this better, but are new to Powershell, I'll explain the above script in a little more detail.

Get-ChildItem C:\Users is basically just like C:\> dir C:\Users in DOS, but Powershell deals in and returns everything in the form of objects, not just simple console output. So by the first line reading

Foreach($_ In Get-ChildItem C:\Users)

It means that we are going to go through a loop for each "object" that exists in C:\Users. Since we're not using the -Recurse parameter here, Powershell will only return the first-level directory listing of C:\Users and will not dig down into the subdirectories.

If($_.PSIsContainer) is an If statement that means "if this current object's "PSIsContainer" property is set to True, which is just a fancy way of saying "if this is a directory," then go into this if loop.

So for every subdirectory under C:\Users, we will enter the If loop. So let's say C:\Users has three subdirectories under it: C:\Users\joe, C:\Users\kate, and C:\Users\bill. Those subdirectories may have any number of files and subdirectories under them.

So we will enter the If loop 3 times, so each time will look something like this:

Get-ChildItem <C:\Users\joe> -Recurse | Remove-Item

Get-ChildItem <C:\Users\kate> -Recurse | Remove-Item

Get-ChildItem <C:\Users\bill> -Recurse | Remove-Item

What this line does is get the contents of that subdirectory, and the -Recurse switch is specified so that it drills down through all the subdirectories of joe,kate, and bill.

Then, it takes all those child objects and pipes them to Remove-Item, and you can think of Remove-Item as a fancy alias for del. It deletes all the things.

Make sense?