How to use Powershell to create backups and delete older backups.

I am trying to create a backup power shell script that copies a directory to a server. I also want the script to check the directory and delete any folder older then, lets say 5 days. The script is set up to run daily saving the backup as the the current date. The problem that I am having is that, when the script starts to run, it checks the sub directories of all folders in that directory and deletes any file that modified time is over 5 days even on folders that were just created. Is there any way to have this script only check the root directory and delete it without it drilling down to sub directories and deleting child items from newer backups? Below is my current script.

robocopy "\\Server\Directory" "E:\Backup\$([datetime]::now.ToString('yyyy-MM-dd'))" /e /w:5 /r:5
# Delete all Files in E:\Backup older than 1 day(s)
$Path = “E:\Backup”
$Daysback = “-1”
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path | Where-Object { $_.creationtime -lt $DatetoDelete } | Remove-Item -whatif -Confirm:$false
Charles P. SmithSystems AdministratorAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

oBdACommented:
Assuming that the target folder is exclusively used by this script (no "third-party" folder creation), there's no need to go by the date. You have a naming format for the actual backup folders that lends itself to sorting by date by default. You just enumerate the folders in the backup folder and keep the youngest 5:
$Source = '\\Server\Directory'
$Target = 'E:\Backup'
$KeepDays = 5

& robocopy.exe $Source "$($Target)\$([datetime]::Now.ToString('yyyy-MM-dd'))" /e /w:5 /r:5
Get-ChildItem -Path $Source -Directory |
	Sort-Object -Property Name -Descending |
	Select-Object -Skip $KeepDays |
	Remove-Item -WhatIf -Confirm:$false

Open in new window

0
Charles P. SmithSystems AdministratorAuthor Commented:
I am running the script now and will let you know the result. One error did pop up when attempting to run it. The -directory line was not recognized as a power shell parameter so, I removed it.

Also, Do I have to change
Get-ChildItem -Path $Source
                   to
Get-ChildItem -Path $Target since, I want the $Target directory to delete old folders?
0
oBdACommented:
Sorry, that should of course have indeed been $Target.
And the -Directory error happened because you're still using PS 2.0 from 2009. WMF 5 supports even Windows 7 / Server 2008 R2, so you might want to look into updating that.

$Source = '\\Server\Directory'
$Target = 'E:\Backup'
$KeepDays = 5

& robocopy.exe $Source "$($Target)\$([datetime]::Now.ToString('yyyy-MM-dd'))" /e /w:5 /r:5
Get-ChildItem -Path $Target | Where-Object {$_.PSIsContainer} |
	Sort-Object -Property Name -Descending |
	Select-Object -Skip $KeepDays |
	Remove-Item -WhatIf -Confirm:$false 

Open in new window

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
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.

Charles P. SmithSystems AdministratorAuthor Commented:
I ran the updated script and it seems to have worked. I changed the $KeepDays variable to 2 and it kept the last two backup files. I want to continue testing it for the next 3-4 days just to confirm that it is what I need. If it is, I will mark this as the best solution. Thank you for your help.
0
serialbandCommented:
Setting R:5 seems excessive.  It would be better to run a first pass with R:0 and then run it again.

Also, you can set the level to not traverse all levels of the subdirectory.
/LEV:n : Only copy the top n LEVels of the source tree.

I'd only use robocopy on separate discreet external disks that I would take offline.  For making multiple copies, pay for something like Hard Link Backup to make use of the built in hard links to deduplicate the data and store many more days of backups in that same space.  https://www.lupinho.net/en/hardlinkbackup/
0
Charles P. SmithSystems AdministratorAuthor Commented:
Something like hardlinkbackup software is not currently in the budget which is why I had to use something like robocopy to backup the directories. We already run shadow protect of most of our servers but, this one is new-ish and we don't have a shadow protect license for it so, in the meantime, I am using robocopy. As for the R:5 being excessive, I wanted to make sure that a file/folder was't skipped due to it being locked but, I ran it in R:0 and it had no issues so, I have changed that parameter.
0
serialbandCommented:
Even if you had issues, I would always run a first pass with R:0, otherwise you could severely delay your initial copy.  I would then run a 2nd robocopy to finish up all the missed files.

You really must run robocopy twice anyway if you're actually interested in keeping date and time stamps for your folders.  The folder dates will change with each access or addition of any file directly within the folder.  You really need to run the 2nd pass to fix the time stamps on those folders if you want a "better" copy.
0
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.