# Run as Administrator to access C:\Program Files\WindowsApps
# Ensure script has permissions to modify protected folders
# Set the path to WindowsApps
$windowsAppsPath = "C:\Program Files\WindowsApps"
# Get all MSTeams folders
$teamsFolders = Get-ChildItem -Path $windowsAppsPath -Directory -Filter "MSTeams*" -ErrorAction SilentlyContinue
if ($teamsFolders.Count -eq 0) {
Write-Output "No MSTeams folders found in $windowsAppsPath"
exit
}
# Find the folder with the latest creation time
$latestFolder = $teamsFolders | Sort-Object CreationTime -Descending | Select-Object -First 1
Write-Output "Latest MSTeams folder (will be kept): $($latestFolder.Name)"
# Take ownership and grant permissions for all MSTeams folders
foreach ($folder in $teamsFolders) {
Write-Output "Taking ownership of: $($folder.FullName)"
takeown /f $folder.FullName /r /d y
icacls $folder.FullName /grant Administrators:F /t
}
# Delete all MSTeams folders except the latest one
foreach ($folder in $teamsFolders) {
if ($folder.Name -ne $latestFolder.Name) {
try {
Write-Output "Deleting: $($folder.FullName)"
Remove-Item -Path $folder.FullName -Recurse -Force -ErrorAction Stop
Write-Output "Successfully deleted: $($folder.Name)"
} catch {
Write-Error "Failed to delete $($folder.Name): $_"
}
}
}
Write-Output "Cleanup complete. Only $($latestFolder.Name) remains."