Forum Discussion

flakey321's avatar
flakey321
Copper Contributor
Jan 13, 2024
Solved

How to compare a date to x months ago when only a part month has passed

Hi, I'm wanting to create a monthly archive and keep 4 months worth. Each month i'll create a new folder for this month and remove the oldest. Whilst I have a check in there to just select the oldes...
  • LainRobertson's avatar
    Jan 14, 2024

    flakey321 

     

    Hi, Robert.

     

    Given you're counting previous months and not interested in the day of month, then for the current date, we don't care about the day of month, making the easiest and most consistent approach to simply work from the 1st.

     

    If I assume that in "keeping the last four months" that the current month is one of those four months, meaning anything older than 1st October 2023 should be removed (i.e. we don't care about what date it is in September that the folder was created), then we can run with something like the following example.

     

    Example

    Get-ChildItem -Directory -Path "C:\Temp" |
        Where-Object {
            $_.CreationTime -lt ([datetime]::new([datetime]::Now.Year, [datetime]::Now.Month, 1)).AddMonths(-3)
        } |
            Remove-Item -Recurse -Force;

     

    What we've done here is created a new datetime object based off today's date but adjusted to be the 1st of the month (i.e. 2024-01-01 as if the time of writing).

     

    We then subtract three months from this reference date (since the current month is the fourth month to keep, and you can't practically subtract 0).

     

    Anything older than this new reference date is eligible for removal, so this is what we compare the directory's CreationTime against.

     

    The Sort-Object and Select-Object from your original example aren't necessary.

     

    Cheers,

    Lain

Resources