0

I'm trying to write a script that deletes all folders that are older than 60 days and create a logfile with the folder names in the directory where the folders have been deleted.

What I have now is:

Get-ChildItem -Directory -Path "\\share\dir1\dir2" | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-10) } | 
    Remove-Item -Force -Recurse | Out-File Auto_Clean.log -Append -WhatIf

The output stays like this for ages:

What if: Performing the operation "Output to File" on target "C:\users\bgijbels\Downloads\Auto_Clean.log".

When I remove the part for Out-File it works fine. It seems like the Out-File part is trying to write the name of every file in the folder to the log, while I only need to have the folder name. I think that's why it takes so long, if at all it gets past the part of creating the logfile. Any ideas? Thank you for your help.

1 Answer 1

1

You are getting a list of all files because -Recurse switch enumerates contents of folders so it can be deleted prior to the root folder removal. Try this:

Get-ChildItem -Directory -Path "\\share\dir1\dir2" | 
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-60) } | % {
        $folder = $_;
        Remove-Item $folder.FullName -Force -Recurse | Out-Null
        $folder.FullName } | 
    Out-File Auto_Clean.log -Append -WhatIf

Directory object is kept as $folder var and you effectively echo its full path after deletion. Obviously take -WhatIf off the end after you are happy with results.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your help Raf. This will probably work when you run the sript in the same directory as where to remove the folders. Now it's complaining it can't find the folders to remove, because it looks in the script path and not on the UNC-Paht of the object to remove. Is the best way to solve this to store the path in a variable? Or to set the script path?
Amended the answer, it now runs Remove-Item against the full UNC path.
Hi Raf, I just tested the enhanced solution but it's still stuck on creating the Output file. So I believe for one reason or another it's still trying to write all the filenames (+2000) in the logfile instead of the folder names. I copied it one on one, so I'm sure I didn't make a mistake there.
It is the -WhatIf switch which is making you stuck, remove that and you will see correct result.
Now I see it.. When I copy a folder with over 2000 files in my test directory and try it there without -whatif, I can see that the script is deleting file after file and not the whole folder at once. So it takes ages to have the folders removed :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.