Setting random Expiry Times for KeePass Entries

I've been using KeePass for years. A while ago I also started using the expire function. However, only a handfull of my accounts actually have this turned on so far. I've been meaning to go through and set this up for all entries, but it's been terribly difficult. I don't want to just turn it on and have all of them be expired, nearly 500 entries! I don't want to do it by hand, that would take forever. I want them randomly spread out so I'm not resetting hundreds of passwords. I might be able to do this via XML export and some kind of perl regex replacement script, what a pain though...

Enter PowerShell! I have a very love-hate relationship with it, but it seems like I use it more and more. In this case I modified a script I found for changing the expiration date, with one I found for creating random dates between a range. You also need the KPScript file in your KeePass directory. Here's the final result.

##################################
### Backup your password file! ###
### Edit these items as needed ###
##################################
$kps  = 'C:\Program Files (x86)\KeePass Password Safe 2\KPScript.exe'
$kdbx = '<your keepass file>'
$pass = '<your password>'

# Get entries
$output = & "$kps" -c:ListEntries "$kdbx" -pw:$pass
$pattern = 'UUID: '
$uuids = $output | Select-String -pattern $pattern

$count = $uuids.Matches.Count

# Update each entry
foreach ($match in $uuids) {

    [DateTime]$theMin = [DateTime]::Now
    [DateTime]$theMax = [DateTime]::Now.AddDays(365)

    $theRandomGen = new-object random
    $theRandomTicks = [Convert]::ToInt64( ($theMax.ticks * 1.0 - $theMin.Ticks * 1.0 ) * $theRandomGen.NextDouble() + $theMin.Ticks * 1.0 )
    $newDate = new-object DateTime($theRandomTicks)

    echo "$count items remaining"
    $count = $count - 1
    $uuid = $match.Line.Substring($pattern.Length)
    $output = & "$kps" -c:EditEntry "$kdbx" -pw:$pass -refx-UUID:"$uuid" -setx-Expires:"true" "-setx-ExpiryTime:$newDate"
}

$x = Read-Host -Prompt 'Finished - Press Enter to continue'

It takes 3-4 seconds to change each item, but oh my it is so much easier than doing it by hand!

Now, this will change everything in your database, so if you have a few you have setup that you don't want to expire, or you want to expire at a certain time, you'll have to manually correct those after.