Link to home
Start Free TrialLog in
Avatar of nopainnogain1
nopainnogain1

asked on

Delete files by date and character count

I have an interesting problem. I need to delete directories that are older than folder 5 days but are only numerical. We have a log folder that has log files that we need to delete but other files are also stored in here. Normally i would do PS scripts to delete all directories over x amount of days but i can delete all folders. I only need to delete folders that are fully numeric.

Wanted to see if anyone had any ideas?
Avatar of Rob Stone
Rob Stone
Flag of United Kingdom of Great Britain and Northern Ireland image

Are the folder names the same character length and display?  

Regex is the way to identify it.

Here is an example script which can identify numerical folders (if there is only one block of numbers). You can change the Regex based on what you have in your file system.  

$a = gci C:\Temp |? Mode -match d
$a.Name
$Regex = "\d+"
Foreach ($dir in $a){
    $b=$dir.Name -match $Regex
    if ($b -eq $true){
        $c=$Matches[0] -eq $dir.Name
        if ($c -eq $true){
            $Name = $dir.Name
            Write-Host "$Name identified for deleting"
        }
    }
}

Open in new window

Avatar of footech
I think Rob Stone is correct about Regex being the way to handle this.  But I think the code can be simplified a fair amount.
Get-ChildItem C:\Temp | Where { $_.PsIsContainer -and $_.Name -match "^\d+$" -and $_.LastWriteTime -gt ((Get-Date).AddDays(-5)) }

Open in new window


Only confusing thing for me is that you go back and forth between talking about files and folders/directories.
ASKER CERTIFIED SOLUTION
Avatar of nopainnogain1
nopainnogain1

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And you didn't here?
Avatar of nopainnogain1
nopainnogain1

ASKER

This gave me a great starting point. It only deleted folders that were numeric