Introduction
I recently came across a need to clear Teams cache. While the task might be simple, I ended up spending a little more time to address the scenarios I can foresee so the PowerShell script is more useful that a single use case.
In this blog post, we’ll be examining this script and also highlight how I applied PowerShell best practices in the process.
Code Overview
The script begins with a comment block that provides a synopsis, description, parameters, example usage, disclaimer, and notes about the script. This is a common practice in PowerShell to provide detailed information about what the script does, how to use it, and who authored it.
<#
.SYNOPSIS
Clears the cache for Microsoft Teams (New Client).
…
.NOTES
Author: Bhargav Shukla
Date: 01/29/2024
#>
Parameters
The use of parameters in the script allows users to customize its behavior. This is a best practice in PowerShell as it makes scripts more flexible and reusable. The parameters are defined using the `param` keyword and include default values, another best practice as it makes the script easier to use and more robust.
param (
[bool]$cacheCleared = $false,
[string]$logFilePath = “C:\Logs\CacheLog.txt”,
[string]$errorFilePath = “C:\Logs\ErrorLog.txt”
)
PowerShell Best Practices in the Code
1. **Commenting**: The script begins with a comprehensive comment block that provides a synopsis, description, parameters, example usage, disclaimer, and notes about the script. This is a best practice as it makes the script self-documenting, which is crucial for maintenance and collaboration.
3. **Default Parameter Values**: The parameters are defined with default values. This is a best practice as it makes the script easier to use and more robust. It also provides a fallback in case the user does not provide a value.
4. **Data Types**: The script specifies the data types for each parameter (`bool` for `$cacheCleared` and `string` for `$logFilePath` and `$errorFilePath`). This is a best practice as it ensures that the script receives the correct types of data.
5. **Code Reusability**: The script uses functions and variables to avoid repeating code and optimize script structure as well.
Complete Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | <# .SYNOPSIS Clears the cache for Microsoft Teams (New Client). .DESCRIPTION This script sets the variable $cacheCleared to $false, indicating that the cache has not been cleared yet. .PARAMETER cacheCleared A boolean variable that indicates whether the cache has been cleared or not. .PARAMETER logFilePath Specifies the path where the log file will be created. .PARAMETER errorFilePath Specifies the path where the error file will be created. .EXAMPLE Clear-NewTeamsCache.ps1 -logFilePath "C:\Logs\CacheLog.txt" -errorFilePath "C:\Logs\ErrorLog.txt" Clears the cache for Microsoft Teams and creates a log file at the specified path. .DISCLAIMER This script is provided as-is without any warranty or support. Use it at your own risk. The author and Microsoft shall not be liable for any damages or losses arising from the use of this script. .NOTES Author: Bhargav Shukla Date: 01/29/2024 #> param ( [bool]$cacheCleared = $false, [string]$logFilePath = "C:\Logs\CacheLog.txt", [string]$errorFilePath = "C:\Logs\ErrorLog.txt" ) # Define cache folder paths $newCacheFolder = "$env:userprofile\appdata\local\Packages\MSTeams_8wekyb3d8bbwe\LocalCache\Microsoft\MSTeams" $classicCacheFolder = "$env:userprofile\appdata\roaming\Microsoft\Teams" # Function to create a file if it doesn't exist function Create-FileIfNotExists { param ( [string]$filePath ) if (-not (Test-Path -Path $filePath)) { New-Item -Path $filePath -ItemType File -Force | Out-Null } } # Function to clear cache function Clear-Cache { param ( [string]$cacheFolder ) Remove-Item -Path $cacheFolder\* -Force -Recurse Write-Host "Cache cleared from $cacheFolder" Add-Content -Path $logFilePath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Cache cleared from $cacheFolder" } # Create log and error files if they don't exist Create-FileIfNotExists -filePath $logFilePath Create-FileIfNotExists -filePath $errorFilePath # Prompt user to clear cache or defer $choice = Read-Host "Do you want to clear the Teams cache now? (Y/N)" if ($choice -eq "Y" -or $choice -eq "y") { try { # Check which version of Teams client is running $teamsProcess = Get-Process -Name "MS-Teams" -ErrorAction SilentlyContinue if ($teamsProcess -eq $null) { $teamsProcess = Get-Process -Name "Teams" -ErrorAction SilentlyContinue } if ($teamsProcess -ne $null) { # Quit Teams application Stop-Process -Id $teamsProcess.Id -Force # Delete cache files based on the client version if ($teamsProcess.Name -eq "MS-Teams") { Clear-Cache -cacheFolder $newCacheFolder } else { Clear-Cache -cacheFolder $classicCacheFolder } # Notify user to start Teams Write-Host "Teams cache cleared. You can now start Teams." # Log the action Add-Content -Path $logFilePath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Cache Cleared" } else { # Clear cache if Teams is not running $clientMessage = "Teams application is not running." Write-Host $clientMessage Add-Content -Path $logFilePath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $clientMessage" # Verify existence of cache folder(s) and clear cache if (Test-Path -Path $newCacheFolder) { Clear-Cache -cacheFolder $newCacheFolder } else { Clear-Cache -cacheFolder $classicCacheFolder } } } catch { # Log error if cache clearing fails $errorMessage = "Failed to clear cache. Error: $($_.Exception.Message)" Write-Host $errorMessage Add-Content -Path $logFilePath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $errorMessage" } finally { # Perform cleanup operations here if needed } } else { # Log the action Add-Content -Path $logFilePath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Cache Clearing Deferred" } |