src/Public/Clear-DownloadsFolder.ps1

#Requires -RunAsAdministrator

<#
.SYNOPSIS
Clears files from the Downloads folders based on specified criteria.
 
.DESCRIPTION
The Clear-DownloadsFolders function is designed to help manage disk space by clearing files from Downloads folders. It can operate on Downloads folders located within user profiles in a specified Organizational Unit (OU) or a specific path. The function supports clearing files older than a specified number of days.
 
.PARAMETER OU
Specifies the Organizational Unit (OU) whose user profiles' Downloads folders will be cleared. This parameter is mandatory if the Path parameter is not provided. The OU must be in the format "OU=xxx,DC=domain,DC=com".
 
.PARAMETER Path
Specifies a specific path to a Downloads folder to be cleared. This parameter is mandatory if the OU parameter is not provided. It will search down up to 3 levels for Downloads folders.
 
.PARAMETER DaysToKeep
Specifies the number of days for which files should be kept in the Downloads folders. Files older than this number of days will be deleted. The default value is 365 days.
 
.EXAMPLE
PS> Clear-DownloadsFolders -OU "OU=Users,DC=example,DC=com" -DaysToKeep 30
 
This example clears files older than 30 days from the Downloads folders of user profiles in the "OU=Users,DC=example,DC=com" OU.
 
.EXAMPLE
PS> Clear-DownloadsFolders -Path "C:\Users\ExampleUser" -DaysToKeep 60
 
This example clears files older than 60 days from the specified Downloads folder path.
 
.EXAMPLE
PS> Clear-DownloadsFolders -Path "D:\UserData\Home\" -DaysToKeep 60
 
This example clears files older than 60 days from all user home folders. It will search down up to 3 levels, so in this case would get Student and Office downloads folders as well.
 
.NOTES
Requires administrative privileges to run. Requires the ActiveDirectory module to run with the OU parameter.
 
#>


function Clear-DownloadsFolder {
    [CmdletBinding(DefaultParameterSetName = "OU")]
    param (
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "OU")]
        [ValidateNotNullOrEmpty()]
        [string]$OU,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = "Path")]
        [ValidateNotNullOrEmpty()]
        [string]$Path,

        [Parameter()]
        [ValidateScript({ $_ -match '^\d+$' })]
        [int]$DaysToKeep = 365
    )

    Begin {

        # Validate Parameters

        If ($OU) {
            # Check if AD Module is available
            try {
                Import-Module ActiveDirectory -ErrorAction Stop
            }
            catch {
                Throw "The ActiveDirectory module is required to run this function with the -OU parameter. If you wish to use this parameter then run the script directly on an Active Directory server or install AD RSAT tools."
            }

            If (-not( $OU -match '^(OU=[^,]+,)+((DC=[^,]+,?)+)$' )) {
                Throw "The specified OU is not valid. Please provide a valid OU."
            }
            $OUExists = Get-ADOrganizationalUnit -Filter { DistinguishedName -eq $OU }
            If (-not $OUExists) {
                Throw "The specified OU does not exist. Please provide a valid OU."
            }
        }

        If ($Path) {
            If (-not ($Path -Match '^(?:[a-zA-Z]:\\[^<>:"/\\|?*\r\n]+|\\\\[^<>:"/\\|?*\r\n]+\\[^<>:"/\\|?*\r\n]+)$')) {
                Throw "Path is not valid. Please provide a valid path."
            }
            If (-not (Test-Path $Path)) {
                Throw "The specified path does not exist. Please provide a valid path."
            }
        }
    }

    Process {
        If ($OU) {
            $Users = Get-ADUser -Filter * -SearchBase $OU -properties *
            Foreach ($User in $Users) {
                $DownloadsFolder = "$($User.HomeDirectory)\Downloads"
                If (Test-Path $DownloadsFolder) {
                    Get-ChildItem $DownloadsFolder | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DaysToKeep) } | Remove-Item -Recurse -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference
                }
            }
        }

        If ($Path) {
            $DownloadsFolders = Get-ChildItem $Path -Directory -Recurse -Depth 2 | Where-Object { $_.Name -eq "Downloads" }
            Foreach ($Folder in $DownloadsFolders) {
                Get-ChildItem $Folder.FullName | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$DaysToKeep) } | Remove-Item -Recurse -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference
            }
        }
    }

    End {

    }
}