powershell script that deletes older file in a directory running as a service

I need a Windows PowerShell script that will delete all the files that are over 2 weeks old in a directory and all subdirectory without deleting the subdirectories.

I then need to convert it to a service so that it is running in the background.
MMICAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Timothy McCartneySYS ADMINISTR I INFRASCommented:
param($ParentDirectory)
$Items = Get-ChildItem -Path $ParentDirectory -File -Recurse

foreach ($Item in $Items){
    if ($Item.LastWriteTime -lt $((Get-date).AddDays(-14))) {
        try {
            Remove-Item $Item.VersionInfo.FileName -Force
        }
        catch {
            Write-Host "Couldn't remove $Item"
            Write-Error $_
        }
    }
}

Open in new window


Instead of installing it as a service, it would be easier to set it to run as a scheduled task.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MMICAuthor Commented:
Thanks for your quick response.  I have two questions here.

Where is the Directory specified?
I see that you have Write-Host "Couldn't remove $Item"
            Where does this write too?  Could this be set to write to a text file in the same folder?

If it is a scheduled task it would require no user intervention.

Also won't recurse make it delete the subfolders?
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
To add it as a scheduled task, Specify the Action as: Start a program
Then type
powershell.exe 

Open in new window

into the Program/script: field
And in the Add arguments (optional): field, type:
-noprofile -file "C:\SomeFolder\Script.ps1" -ParentDirectory "C:\PathToDirectoryToDeleteFiles"

Open in new window

0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

Timothy McCartneySYS ADMINISTR I INFRASCommented:
Where is the Directory specified?
This is passed as a parameter to the Script. You could run it directly from a powershell console by using the cd command to get to the directory that you created the script and then typing:
.\Script.ps1 -ParentDirectory C:\Path\To\Folder

Open in new window

This assumes you named the script
Script.ps1

Open in new window


I see that you have Write-Host "Couldn't remove $Item"
            Where does this write too?  Could this be set to write to a text file in the same folder?
This would write directly to an active powershell console. You could replace that line with:
"Couldn't remove $($Item) - Error Message: $($_)" | Out-File C:\SomeFolder\log.txt -Append

Open in new window


If it is a scheduled task it would require no user intervention.
This is true. You would store credentials to have the task run automatically.

Also won't recurse make it delete the subfolders?
I also included the -File parameter, which specifies that Get-ChildItem will only collect Files and exclude directories.
0
MMICAuthor Commented:
ok.. I think that I almost understand it..

My only concern is that I will store the script in S:\Scripts

The files I want removed are in

S:\Backups

I am adding this as a scheduled tasks or as a service

Where can I add the logic for the script to run in s:\Backups\
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
In your case, you would use the following snippet in the arguments field of the scheduled task
-noprofile -file "S:\Scripts\Remove-OldBackups.ps1" -ParentDirectory "S:\Backups"

Open in new window

Example Scheduled Task
0
MMICAuthor Commented:
whould this work?

param($ParentDirectory)
$ParentDirectory = "S:\PhoneBackup\"
$Items = Get-ChildItem -Path $ParentDirectory -File -Recurse

foreach ($Item in $Items){
    if ($Item.LastWriteTime -lt $((Get-date).AddDays(-14))) {
        try {
            Remove-Item $Item.VersionInfo.FileName -Force
        }
        catch {
            "Couldn't remove $($Item) - Error Message: $($_)" | Out-File s:\PhoneBackup\FailedLog.txt -Append
            Write-Error $_
        }
    }
}
0
MMICAuthor Commented:
I think we posted at the same time :-)
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Haha, indeed :)

The param($ParentDirectory) is configured as a script parameter, this means you can pass the directory to it as the script is ran, which enables you to use this same script to cleanup other directories in the future (if you choose).

Alternately, you could set a default parameter value
param($ParentDirectory = "S:\Backups")

Open in new window

0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Use this :)

param($ParentDirectory="S:\Backups")
$Items = Get-ChildItem -Path $ParentDirectory -File -Recurse

foreach ($Item in $Items){
    if ($Item.LastWriteTime -lt $((Get-date).AddDays(-14))) {
        try {
            Remove-Item $Item.VersionInfo.FileName -Force
        }
        catch {
            Write-Host "Couldn't remove $Item"
            Write-Error $_
        }
    }
}

Open in new window

0
MMICAuthor Commented:
Thank you very much!!!
0
Timothy McCartneySYS ADMINISTR I INFRASCommented:
Happy to help! I want add that you should utilize my last snippet in your script since it sets the -ParentDirectory parameter automatically
0
MMICAuthor Commented:
yes.. I ended up with

param($ParentDirectory="S:\PhoneBackup")
$Items = Get-ChildItem -Path $ParentDirectory -File -Recurse

foreach ($Item in $Items){
    if ($Item.LastWriteTime -lt $((Get-date).AddDays(-14))) {
        try {
            Remove-Item $Item.VersionInfo.FileName -Force
        }
        catch {
            "Couldn't remove $($Item) - Error Message: $($_)" | Out-File s:\PhoneBackup\FailedLog.txt -Append
            Write-Error $_
        }
    }
}
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.