param ( [Parameter(Mandatory=$true,ParameterSetName='itunesbackups')] [int]$iTunesBackups=$false, [Parameter(Mandatory=$false,ParameterSetName='itunesbackups')] [int]$OlderThan=0) Function Delete-iTunesBackups($dir) { ## Create a new timespan to compare with last write date of the target directory $timedelta = New-TimeSpan -Days $OlderThan ## Get each iTunes backup directory Foreach ( $d in (Get-ChildItem -Path $dir) ) { ## If it's older than the number of days specified, recursively delete the directory If ( $d.LastWriteTime -lt ((Get-Date) - $timedelta) ) { Remove-Item $d.FullName -Recurse -Force } } } ## Process each user's directory If ( $iTunesBackups ) { ## List of accounts to exclude $ExcludedUsers = @("Public", "All Users") ## Empty array to hold the user directories to clean $DirectoriesToProcess = @() ## Get all user accounts in ${Env:SystemDrive}\Users $UsersPath = "${Env:SystemDrive}\Users" Get-ChildItem -Attributes Directory -Path $UsersPath | ForEach-Object { $username = $_.Name $path = "${UsersPath}\${username}\AppData\Roaming\Apple Computer\MobileSync\Backup" ## Make sure the user isn't excluded and that the iTunes backup directory exists If ( ($ExcludedUsers -notcontains $username) -and (Test-Path -PathType Container -Path $path) ) { ## Make sure there's data in the iTunes backup folder If ( (Get-ChildItem $path | Measure-Object).Count -gt 0 ) { ## Call the Delete-iTunesBackups function for each directory Delete-iTunesBackups $path } } } }