Search code examples
powershellglobget-childitem

powershell script to delete files based on start of file name


So i have files in a folder that start with

1__

and

0__

example files

1__shal1absahal9182skab.php
0__abns1a3bshal54a4m5sb.php

i am trying to get my powershell script to only delete files of 1__ that are older than 60 mins while 0__ can be deleted every 360 mins.

here is my current code

$limit = (Get-Date).AddMinutes(-360)
$path = "C:\cache"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

my script currently treats both files as the same and deletes them both on 360 minute intivals.


Solution

  • Found a solution using if and else with some regex pattern matching.

    $limit_guest = (Get-Date).AddMinutes(-360) #6 hours
    $limit_logged_in = (Get-Date).AddMinutes(-60) #1 hours
    $path = "C:\cache"
    
    # Delete files older than the $limit.
    Get-ChildItem -Path $path -Recurse -Force | Where-Object { if ( $_ -match "^0__.*" ) { !$_.PSIsContainer -and $_.CreationTime -lt $limit_guest } else { !$_.PSIsContainer -and $_.CreationTime -lt $limit_logged_in } } | Remove-Item -Force
    
    # Delete any empty directories left behind after deleting the old files.
    Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse