A folder contain ‘n’ number of files. In that, I want to delete only file names which starts with ‘Tcp’, that too which are older than 30 days and latest files should remain as it is. I have a script but its deleting all the tcp files inside the folder.
But need to delete only files, whose name starts with TCP, which are created 30 days back.
It’d be better for you to bring some code that you’ve written and ask a specific question about it. We’re not set up to write complete solutions for you. If you’re having trouble just understanding the logic you’d use, it’s fine to ask that, too - folks can outline the logical steps they’d use. But, to echo the previous comment, this is something that’s been asked here hundreds of times - it might be worth a search of the forums to see what’s already been asked and answered.
I searched and got couple of answer for above query, even i altered the script too but script didn’t worked as expected, its deleting all the files inside the folder.
Some minor changes and condition to be included on the script, am not getting that.
So thought to post it here.
As i am very new to PS, i am trying to learn the things.
Means “everything more than a minute old”. Sure the comparison is ‘lt’ (less than) but in a date value comparison [less than one minute ago] means everything earlier than whatever one minute ago was.
That’s what you’re targeting and deleting here.
So you need to change your condition to match your requirements:
$limit = (Get-Date).AddDays(-30)
$Name = "Tcp*"
$Files = Get-Childitem $TargetFolder -Include $Name #... rest of the script
But i was trying in my local server instead of production, instead of testing for 30 days i was trying for minutes.
I was testing, which ever the files are created less than 1 minutes, it should not get deleted and older files should get deleted.
especially the file name starts from “tcp.*”. but here all the files are getting deleted.
I have tried, even though it didn’t worked.
Please help me out.
Include and Exclude for Get-ChildItem don't always work as expected and are typically extensions. It's better to do the filter in the path or in a Where filter after you get all files. We always try to filter left, so we'll use the path
The Where filter in this case is looking for files less than a date that we subtracted 30 days from
We can then pipe this to Remove-Item. Use the WhatIf switch to see what will be deleted rather than delete the files.
In the above sample files, only tcp.3ndc.21.txt and tcp.23.c21.txt should be deleted. But in my case, even tcp.txt is being deleted. Can you please guide me on this?