
# Set the maximum allowed age of Revit local files
$FileAllowedAge = (Get-Date).AddMonths(-1)

# Build all Revit local paths
$RevitLocalPaths = @()
ForEach ( $userProfile in (Get-ChildItem -Path "${Env:SystemDrive}\Users" | Where-Object { $_.PSIsContainer }) ) {
    $profilePath = $userProfile.FullName
    If ( Test-Path "${profilePath}\Documents\Revit Locals" ) { $RevitLocalPaths += ,@("${profilePath}\Documents\Revit Locals") }
    If ( Test-Path "${profilePath}\Documents" )              { $RevitLocalPaths += ,@("${profilePath}\Documents") }
}

ForEach ( $path in $RevitLocalPaths ) {
    $RevitFiles = Get-ChildItem -Path "${path}\*.*" -Filter '*.rvt' | Where-Object {$_.LastWriteTime -lt $FileAllowedAge}
    If ( $RevitFiles ) {
        ForEach ($revitfile in $RevitFiles) {

            $parentDir = $revitfile.DirectoryName
            $baseName = $revitfile.BaseName
            $BackupDir = "${parentDir}\${basename}_backup"

            # Only remove Revit local files that have worksharing enabled
            If ( (Test-Path "${revitfile}") -and (Test-Path "${BackupDir}")) {
                LogMsg "Deleting ""${revitfile}"" and backup directory ""${BackupDir}"""
                Remove-Item "${revitfile}" -Force -ErrorAction SilentlyContinue
                Remove-Item "${BackupDir}" -Recurse -ErrorAction SilentlyContinue
            }
        }
    }
}