├── CurrentVersion.txt ├── Poor_System_Performance.ps1 └── README.md /CurrentVersion.txt: -------------------------------------------------------------------------------- 1 | 1.7.9.1 2 | -------------------------------------------------------------------------------- /Poor_System_Performance.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .NOTES 3 | =========================================================================== 4 | Created on: 20160901 5 | Created by: Josh Meyer 6 | Organization: Helion Technologies 7 | Filename: PSP.VERSION.ps1 8 | =========================================================================== 9 | .DESCRIPTION 10 | This script is designed to clean up un-needed cache, cookies and other temporary files from the computer. 11 | 12 | Parameters: 13 | -"-Optimizations" 14 | Switches: 15 | -"Kaseya" 16 | -"Users" 17 | -"Offboarding" 18 | -"SFC" 19 | -"DISM" 20 | Explanation: 21 | When Kaseya is provided, the script will check for HDD space and determine if it should run, or exit. 22 | Example: PSP.VERSION.ps1 -Optimizations Kaseya 23 | When Users is provided, the script will remove user folders for anyone that has not logged in in the last 30 days. 24 | Example: PSP.VERSION.ps1 -Optimizations Users 25 | 26 | Explanation of Functions: 27 | InstallCMTrace; Download and install Microsoft's CMTrace log viewing tool from SCCM. 28 | DiskSpaceBefore; Captures disk space before the script removes any files. 29 | ProcessWarning; Checks for open processes that will interfere with the script. 30 | ProcessTermination; Closes all open processes that will interfere with the script. 31 | DiskCleanup; Launches Microsoft Disk Cleanup (cleanmgr) and sets flags for all items that it's capable of cleaning. 32 | Win10UpgradeCleanup; Removes all files related to the Windows 10 Upgrade project. 33 | CleanCTemp; Checks folder size and deletes files older than 30 days old if folder is over 1GB. 34 | CleanIISLogFiles; Cleans IIS Log files older than 14 days old. 35 | StartupItems; Reports on Startup items. (IN PROGRESS) 36 | UserCleanup; Removes Users that have not logged into the computer in over 30 days. 37 | GPUpdate; Runs GPUpdate. 38 | FlushDNS; Flushes DNS. 39 | IECleanup; Removes Cookies and Cache from IE. 40 | ChromeCleanup; Removes Cookies and Cache from Chrome. 41 | FirefoxCleanup; Removes Cookies and Cache from Firefox. 42 | UserTempFiles; Removes User specific temp files. 43 | JavaCache; Removes Java cookies and cache. 44 | AdobeAcrobat; Removes Adobe Acrobat cookies and cache. 45 | AdobeFlash; Removes Adobe Flash cookies and cache. 46 | OfficeCleanup; Removes cache from Office applications. 47 | SystemFiles; Removes System level log and temp files (NOT Event Viewer logs). 48 | HelionUSMT; Checks for and removes the Helion USMT folder. 49 | 50 | DiskCleanupCheck; Checks to see if Disk Cleanup is running and waits for it to complete if it is. 51 | DiskSpaceAfter; Captures disk space after the script removes files. 52 | Housecleaning; Reporting on script results. 53 | ScriptEnding; Removing script files and stop logging. 54 | WorkstationRestart; Prompts for logout and restart options. 55 | 56 | TASKS: 57 | Add Event Viewer entries for functions. 58 | Allow log file to be defined with a parameter. Default to what's defined if the parameter isn't provided. 59 | #> 60 | ################ 61 | ## Parameters ## 62 | ################ 63 | #region Parameters 64 | ## 20200720.jmeyer.Adding Parameters to combine several versions of the script. 65 | ## 20230811.Added autoupdating. 66 | Param ( 67 | [parameter(Mandatory = $false, Position = 0)] 68 | [bool]$Optimizations = $false, 69 | [parameter(Mandatory = $false)] 70 | [bool]$Kaseya = $false, 71 | [parameter(Mandatory = $false)] 72 | [bool]$AutoUpdate = $true 73 | ) 74 | #endregion Parameters 75 | ############# 76 | ## Modules ## 77 | ############# 78 | #region Modules 79 | Write-Host "Setting up Modules..." -ForegroundColor Yellow 80 | #Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted 81 | ## 20211012.jmeyer.Adjusted AD Module installation as this varies with Windows 10 builds. 82 | ## older than 1809: "Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell" 83 | ## 1809 and newer: "Add-WindowsCapability –online –Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0"" 84 | if (Get-Module -ListAvailable -Name ActiveDirectory) 85 | { 86 | Write-Host "ActiveDirectory Module is installed." -ForegroundColor Green 87 | } 88 | else 89 | { 90 | Add-WindowsCapability -Online -Name "Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0" 91 | #Get-WindowsCapability -Name "RSAT*" -Online | Add-WindowsCapability -Online 92 | Import-Module ActiveDirectory 93 | } 94 | 95 | #if (Get-Module -ListAvailable -Name PSWriteHTML) 96 | #{ 97 | # Write-Host "PSWriteHTML Module is already installed." -ForegroundColor Green 98 | #} 99 | #else 100 | #{ 101 | # Install-Module -Name PSWriteHTML -Force 102 | # Import-Module PSWriteHTML 103 | #} 104 | Write-Host "Finished setting up Modules." -ForegroundColor Green 105 | #endregion Modules 106 | ############### 107 | ## Functions ## 108 | ############### 109 | #region Functions 110 | Write-Host "Setting Functions..." -ForegroundColor Yellow 111 | ## 20200811.jmeyer.Created Functions for efficiency, Kaseya automated deployment, and combining Server and Workstation cleanups into one script. 112 | Write-Host "Setting up..." -ForegroundColor Yellow 113 | Write-Host "Setting up security protocols..." -ForegroundColor Yellow 114 | [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls12; 115 | Write-Host "Creating Functions..." -ForegroundColor Yellow 116 | #region StandardFunctions 117 | function InitialSetup 118 | { 119 | ## Event log logging 120 | try 121 | { 122 | New-EventLog -LogName Application -Source "$ScriptName" -ErrorAction Stop 123 | } 124 | catch [System.InvalidOperationException] 125 | { 126 | Write-Host "Event Log Source for this script is already registered." -ForegroundColor Green 127 | } 128 | $StartTime = Get-Date 129 | Write-EventLog -Message "The $ScriptFullName script was started." -EventID 32700 -EntryType Information -LogName "Application" -Source "$ScriptName" -Category 1 -RawData 10, 20 130 | ## Setting colors for various messages. 131 | $SetColors = (Get-Host).PrivateData 132 | $SetColors.WarningBackgroundColor = "Red" 133 | $SetColors.WarningForegroundColor = "White" 134 | $SetColors.DebugBackgroundColor = "White" 135 | $SetColors.DebugForegroundColor = "DarkBlue" 136 | $SetColors.VerboseBackgroundColor = "Red" 137 | $SetColors.VerboseForegroundColor = "White" 138 | #$DebugPreference = 'Continue' 139 | } 140 | function Logging 141 | { 142 | if ($PSVersionTable.PSVersion.Major -ge 3) 143 | { 144 | Write-Host "We are running Powershell version 3 or greater. Logging enabled." -ForegroundColor Green 145 | if ((Test-Path C:\Logs\) -eq $false) 146 | { 147 | $null = New-Item C:\Logs\ -ItemType Directory 148 | } 149 | $LogFile = "C:\Logs\$ScriptFullName.$(Get-Date -UFormat %Y%m%d).log" 150 | Start-Transcript -Path $LogFile 151 | Write-EventLog -Message "Logging started for $ScriptFullName and can be located at $LogFile." -EventID 32702 -EntryType Information -LogName "Application" -Source "$ScriptName" -Category 1 -RawData 10, 20 152 | } 153 | } 154 | function AdminElevation 155 | { 156 | Write-Host "Checking for administrative rights..." -ForegroundColor Yellow 157 | ## Get the ID and security principal of the current user account. 158 | $myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent(); 159 | $myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID); 160 | ## Get the security principal for the administrator role. 161 | $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator; 162 | 163 | ## Check to see if we are currently running as an administrator. 164 | if ($myWindowsPrincipal.IsInRole($adminRole)) 165 | { 166 | ## We are running as an administrator, so change the title and background colour to indicate this. 167 | Write-Host "We are running as administrator, changing the title to indicate this." -ForegroundColor Green 168 | $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"; 169 | } 170 | else 171 | { 172 | Write-Host "We are not running as administrator. Relaunching as administrator." -ForegroundColor Yellow 173 | ## We are not running as admin, so relaunch as admin. 174 | $NewProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell"; 175 | ## Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path. 176 | $NewProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'" 177 | ## Indicate that the process should be elevated. 178 | $NewProcess.Verb = "runas"; 179 | ## Start the new process 180 | [System.Diagnostics.Process]::Start($newProcess); 181 | ## Exit from the current, unelevated, process. 182 | Exit; 183 | } 184 | Write-Host "Continuing with setup..." -ForegroundColor Yellow 185 | } 186 | function AutoUpdate() 187 | { 188 | if ($AutoUpdate) 189 | { 190 | Write-Host "Auto Updates are enabled. Checking for updates..." 191 | if (Test-Connection 8.8.8.8 -Count 1 -Quiet) 192 | { 193 | Write-Host "Internet connection verified..." 194 | $UpdateAvailable = $false 195 | $NewVersionNumber = $null 196 | try 197 | { 198 | Write-Host "Checking for newer version..." 199 | ## For use with PUBLIC GitHub Repos 200 | [version]$NewVersionNumber = (New-Object System.Net.WebClient).DownloadString($GitHubVersion).Trim([Environment]::NewLine) 201 | [version]$CurrentVersionNumber = $ScriptVersionNumber 202 | Write-Host "Version information found..." 203 | Write-Host "Checking version numbers..." 204 | if ($NewVersionNumber -gt $CurrentVersionNumber) 205 | { 206 | Write-Host "Newer version found!" 207 | Write-Host "Current Version: $ScriptVersionNumber" 208 | Write-Host "New Version: $NewVersionNumber" 209 | Write-Host "Update available. Removing existing script and downloading update..." 210 | Remove-Item $PSCommandPath -Force -Verbose 211 | ## For use with PUBLIC GitHub Repos 212 | (New-Object System.Net.Webclient).DownloadFile($NewScriptFile, $PSCommandPath) 213 | Write-Host "Script downloaded. Starting updated script and exiting the current script..." -ForegroundColor Blue 214 | Start-Sleep 5 215 | if ([String]::IsNullOrEmpty($Optimizations)) 216 | { 217 | ## Used if only Optimizations contains data. 218 | Start-Process PowerShell -Arg "$PSCommandPath -AutoUpdate 0 -Optimizations $Optimizations" 219 | ScriptEnding 220 | } 221 | else 222 | { 223 | Start-Process PowerShell -Arg "$PSCommandPath -AutoUpdate 0" 224 | ScriptEnding 225 | } 226 | } 227 | else 228 | { 229 | Write-Host "We are running the latest version. Continuing..." 230 | } 231 | } 232 | catch [System.Exception] 233 | { 234 | Write-Host $_ 235 | } 236 | } 237 | else 238 | { 239 | Write-Host "Unable to check for updates. Internet connection not available." 240 | } 241 | } 242 | } 243 | function Prerequisites 244 | { 245 | ## Script requirements 246 | if ($OSName -like '*server*') 247 | { 248 | Write-Host "We are running on $OSName." -ForegroundColor Yellow 249 | Write-Host "Setting variables to adjust script for server usage." -ForegroundColor Yellow 250 | $ScriptIntelligence = "Server" 251 | Write-Host "Variables set for Server. Continuing..." -ForegroundColor Green 252 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "This script is set to be ran on a Server." -Category 1 -RawData 10, 20 253 | } 254 | else 255 | { 256 | Write-Host "We are running on $OSName." -ForegroundColor Yellow 257 | Write-Host "Setting variables to adjust script for workstation usage." -ForegroundColor Yellow 258 | $ScriptIntelligence = "Workstation" 259 | Write-Host "Variables set for Workstation. Continuing..." -ForegroundColor Green 260 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "This script is set to be ran on a Workstation." -Category 1 -RawData 10, 20 261 | } 262 | } 263 | #endregion StandardFunctions 264 | function UnzipFile 265 | { 266 | <# 267 | .SYNOPSIS 268 | UnzipFile is a function which extracts the contents of a zip file. 269 | .DESCRIPTION 270 | UnzipFile is a function which extracts the contents of a zip file specified via the -File parameter to the 271 | location specified via the -Destination parameter. This function first checks to see if the .NET Framework 4.5 272 | is installed and uses it for the unzipping process, otherwise COM is used. 273 | .PARAMETER File 274 | The complete path and name of the zip file in this format: C:\zipfiles\myzipfile.zip 275 | .PARAMETER Destination 276 | The destination folder to extract the contents of the zip file to. If a path is no specified, the current path 277 | is used. 278 | .PARAMETER ForceCOM 279 | Switch parameter to force the use of COM for the extraction even if the .NET Framework 4.5 is present. 280 | .EXAMPLE 281 | UnzipFile -File C:\zipfiles\AdventureWorks2012_Database.zip -Destination C:\databases\ 282 | .EXAMPLE 283 | UnzipFile -File C:\zipfiles\AdventureWorks2012_Database.zip -Destination C:\databases\ -ForceCOM 284 | .EXAMPLE 285 | 'C:\zipfiles\AdventureWorks2012_Database.zip' | UnzipFile 286 | .EXAMPLE 287 | Get-ChildItem -Path C:\zipfiles | ForEach-Object {$_.fullname | UnzipFile -Destination C:\databases} 288 | .INPUTS 289 | String 290 | .OUTPUTS 291 | None 292 | .NOTES 293 | Author: Mike F Robbins 294 | Website: http://mikefrobbins.com 295 | Twitter: @mikefrobbins 296 | #> 297 | [CmdletBinding()] 298 | param ( 299 | [Parameter(Mandatory = $true, 300 | ValueFromPipeline = $true)] 301 | [ValidateScript({ 302 | If ((Test-Path -Path $_ -PathType Leaf) -and ($_ -like "*.zip")) 303 | { 304 | $true 305 | } 306 | else 307 | { 308 | Throw "$_ is not a valid zip file. Enter in 'C:\Folder\File.zip' format" 309 | } 310 | })] 311 | [string]$File, 312 | [ValidateNotNullOrEmpty()] 313 | [ValidateScript({ 314 | If (Test-Path -Path $_ -PathType Container) 315 | { 316 | $true 317 | } 318 | else 319 | { 320 | Throw "$_ is not a valid destination folder. Enter in 'C:\Destination' format" 321 | } 322 | })] 323 | [string]$Destination = (Get-Location).Path, 324 | [switch]$ForceCOM 325 | ) 326 | If (-not $ForceCOM -and ($PSVersionTable.PSVersion.Major -ge 3) -and 327 | ((Get-ItemProperty -Path "HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full" -ErrorAction SilentlyContinue).Version -like "4.5*" -or 328 | (Get-ItemProperty -Path "HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Client" -ErrorAction SilentlyContinue).Version -like "4.5*")) 329 | { 330 | Write-Verbose -Message "Attempting to Unzip $File to location $Destination using .NET 4.5" 331 | try 332 | { 333 | [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null 334 | [System.IO.Compression.ZipFile]::ExtractToDirectory("$File", "$Destination") 335 | } 336 | catch 337 | { 338 | Write-Warning -Message "Unexpected Error. Error details: $_.Exception.Message" 339 | } 340 | } 341 | else 342 | { 343 | Write-Verbose -Message "Attempting to Unzip $File to location $Destination using COM" 344 | try 345 | { 346 | $shell = New-Object -ComObject Shell.Application 347 | $shell.Namespace($destination).copyhere(($shell.NameSpace($file)).items()) 348 | } 349 | catch 350 | { 351 | Write-Warning -Message "Unexpected Error. Error details: $_.Exception.Message" 352 | } 353 | } 354 | } 355 | function DiskSpaceBefore 356 | { 357 | ## Gather HDD free space prior to cleaning. Used for ticketing purposes. 358 | $env:Before = Get-CimInstance Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | 359 | Select-Object SystemName, 360 | @{ Name = "Drive"; Expression = { ($_.DeviceID) } }, 361 | @{ Name = "Size (GB)"; Expression = { "{0:N1}" -f ($_.Size / 1GB) } }, 362 | @{ Name = "FreeSpace (GB)"; Expression = { "{0:N1}" -f ($_.Freespace / 1GB) } }, 363 | @{ Name = "PercentFree"; Expression = { "{0:P1}" -f ($_.FreeSpace / $_.Size) } } | 364 | Format-Table -AutoSize | Out-String 365 | $env:FSpaceBefore = (Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace / 1GB 366 | } 367 | function ProcessWarning 368 | { 369 | Write-Host "Gathering open processes..." -ForegroundColor Yellow 370 | ## Warning user that the script is going to kill applications and specifies only the open applications that need to be closed. 371 | ## 20210322.jmeyer.Added error action due to changes with how exe's are interacted with. 372 | $OpenProcessesUnique = Get-Process -Name $ProcessList -ErrorAction SilentlyContinue | select -Unique 373 | 374 | if ($Kaseya -notcontains "Yes") 375 | { 376 | if ([bool]($OpenProcessesUnique)) 377 | { 378 | Write-Warning "Please save all work and close the following applications before continuing."; 379 | Write-Warning "If you continue without closing the application, they will be forcefully closed and any unsaved changes will be lost!" 380 | foreach ($Process in $OpenProcessesUnique) 381 | { 382 | $TempProcess = (Get-Process -Name $Process).Product 383 | Write-Host "$($TempProcess[0])" 384 | } 385 | Write-Warning "Press any key to continue..."; 386 | $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown"); 387 | } 388 | else 389 | { 390 | Write-Host "All necessary applications are closed." -ForegroundColor Green; 391 | Write-Host "Continuing..." -ForegroundColor Green; 392 | } 393 | } 394 | else 395 | { 396 | Write-Host "This script was launched from Kaseya, we are unable to warn the user to close the following open processes." -ForegroundColor Red 397 | foreach ($Process in $OpenProcessesUnique) 398 | { 399 | if ([bool](Get-Process -Name $Process)) 400 | { 401 | $TempProcess = (Get-Process -Name $Process).Product 402 | Write-Host "$($TempProcess[0])" 403 | } 404 | } 405 | } 406 | } 407 | function ProcessTermination 408 | { 409 | if ([bool]($OpenProcessesUnique)) 410 | { 411 | Write-Warning "Killing any required processes that are still open..." 412 | $OpenProcesses = Get-Process -Name $ProcessList -ErrorAction SilentlyContinue 413 | foreach ($Process in $OpenProcesses) 414 | { 415 | ## 20190517.jmeyer.Added -Force. 416 | ## 20230201.jmeyer.Added -Verbose 417 | Stop-Process -Name $Process -Force -ErrorAction SilentlyContinue -Verbose 418 | } 419 | } 420 | } 421 | function DiskCleanup 422 | { 423 | ## 20170327.jmeyer.Moved Admin script to main script. Part 1. 424 | ## Stops the Windows Update service. 425 | Stop-Service -Name wuauserv -Force 426 | ## Stops the BITS service. 427 | Stop-Service -Name BITS -Force 428 | ## Running Disk Cleanup, selecting all options that are allowed by Windows. This does NOT alter the registry. 429 | ## 20230131.jmeyer.Added try/catch to handle errors for keys that do not exist. 430 | Write-Host "Starting Disk Cleanup..." -ForegroundColor Yellow 431 | for ($i = 0; $i -lt $TempFolders.Count; $i++) 432 | { 433 | $RegKey = $DirPath + "\" + $TempFolders[$i] 434 | try 435 | { 436 | $StateValue = (Get-ItemProperty $RegKey).$VName 437 | } 438 | catch [System.Management.Automation.ItemNotFoundException] 439 | { 440 | Write-Host "The registry key was not found. Moving on..." -ForegroundColor Yellow 441 | } 442 | if (-not $StateValue) 443 | { 444 | try 445 | { 446 | New-ItemProperty -Path $RegKey -Name $VName -Value "2" -PropertyType "dword" | Out-Null 447 | } 448 | catch [System.Management.Automation.ItemNotFoundException] 449 | { 450 | Write-Host "The registry key was not found. Moving on..." -ForegroundColor Yellow 451 | } 452 | } 453 | else 454 | { 455 | try 456 | { 457 | Set-ItemProperty -Path $RegKey -Name $VName -Value "2" 458 | } 459 | catch [System.Management.Automation.ItemNotFoundException] 460 | { 461 | Write-Host "The registry key was not found. Moving on..." -ForegroundColor Yellow 462 | } 463 | } 464 | $RegKey = $DirPath 465 | } 466 | ## 20210322.jmeyer.Added /SETUP to remove previous installations of Windows. 467 | CLEANMGR /sagerun:32 /SETUP 468 | Write-Host "Disk Cleanup is starting..." -ForegroundColor Green 469 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Disk Cleanup is starting." -Category 1 -RawData 10, 20 470 | } 471 | ## 20200811.jmeyer.Adding cleanup of Windows 10 Upgrade project files on upgraded assets. 472 | function Win10UpgradeCleanup 473 | { 474 | if ($Optimizations -contains "Offboarding") 475 | { 476 | Write-Host "Checking for Windows 10 Upgrade folders..." -ForegroundColor Yellow 477 | if ($Windows10Upgrade) 478 | { 479 | Write-Host "Found Windows10Upgrade folder." -ForegroundColor Green 480 | Write-Host "Removing Windows10Upgrade folder..." -ForegroundColor Yellow 481 | Remove-Item -Path C:\Windows10Upgrade -Force -Recurse 482 | Write-Host "Folder deleted!" -ForegroundColor Green 483 | } 484 | else 485 | { 486 | Write-Host "No Windows10Upgrade found!" -ForegroundColor Red 487 | } 488 | 489 | if ($Win10Upgrade) 490 | { 491 | Write-Host "Found Win10Upgrade folder." -ForegroundColor Green 492 | Write-Host "Removing Win10Upgrade folder..." -ForegroundColor Yellow 493 | Remove-Item -Path C:\Win10Upgrade -Force -Recurse 494 | Write-Host "Folder deleted!" -ForegroundColor Green 495 | } 496 | else 497 | { 498 | Write-Host "No Win10Upgrade found!" -ForegroundColor Red 499 | } 500 | 501 | if ($O365Install) 502 | { 503 | Write-Host "Found O365Install folder." -ForegroundColor Green 504 | Write-Host "Removing O365Install folder..." -ForegroundColor Yellow 505 | Remove-Item -Path C:\O365Install -Force -Recurse 506 | Write-Host "Folder deleted!" -ForegroundColor Green 507 | } 508 | else 509 | { 510 | Write-Host "No O365Install found!" -ForegroundColor Red 511 | } 512 | } 513 | elseif ($OSName -like "*Windows 10*") 514 | { 515 | Write-Host "Checking for Windows 10 Upgrade folders..." -ForegroundColor Yellow 516 | if ($Windows10Upgrade) 517 | { 518 | Write-Host "Found Windows10Upgrade folder." -ForegroundColor Green 519 | Write-Host "Removing Windows10Upgrade folder..." -ForegroundColor Yellow 520 | Remove-Item -Path C:\Windows10Upgrade -Force -Recurse 521 | Write-Host "Folder deleted!" -ForegroundColor Green 522 | } 523 | else 524 | { 525 | Write-Host "No Windows10Upgrade found!" -ForegroundColor Red 526 | } 527 | 528 | if ($Win10Upgrade) 529 | { 530 | Write-Host "Found Win10Upgrade folder." -ForegroundColor Green 531 | Write-Host "Removing Win10Upgrade folder..." -ForegroundColor Yellow 532 | Remove-Item -Path C:\Win10Upgrade -Force -Recurse 533 | Write-Host "Folder deleted!" -ForegroundColor Green 534 | } 535 | else 536 | { 537 | Write-Host "No Win10Upgrade found!" -ForegroundColor Red 538 | } 539 | 540 | if ($O365Install) 541 | { 542 | Write-Host "Found O365Install folder." -ForegroundColor Green 543 | Write-Host "Removing O365Install folder..." -ForegroundColor Yellow 544 | Remove-Item -Path C:\O365Install -Force -Recurse 545 | Write-Host "Folder deleted!" -ForegroundColor Green 546 | } 547 | else 548 | { 549 | Write-Host "No O365Install found!" -ForegroundColor Red 550 | } 551 | } 552 | elseif ($OSName -like "*Server*") 553 | { 554 | Write-Host "Checking for Windows 10 Upgrade folders..." -ForegroundColor Yellow 555 | if ($ServerWin10Upgrade -ne $null) 556 | { 557 | Write-Host "Found Win10Upgrade folder." -ForegroundColor Green 558 | Write-Host "Removing Win10Upgrade folder..." -ForegroundColor Yellow 559 | Remove-Item -Path $ServerWin10Upgrade -Force -Recurse 560 | Write-Host "Folder deleted!" -ForegroundColor Green 561 | } 562 | else 563 | { 564 | Write-Host "No Win10Upgrade found!" -ForegroundColor Red 565 | } 566 | 567 | if ($ServerO365Install -ne $null) 568 | { 569 | Write-Host "Found O365Install folder." -ForegroundColor Green 570 | Write-Host "Removing O365Install folder..." -ForegroundColor Yellow 571 | Remove-Item -Path $ServerO365Install -Force -Recurse 572 | Write-Host "Folder deleted!" -ForegroundColor Green 573 | } 574 | else 575 | { 576 | Write-Host "No O365Install found!" -ForegroundColor Red 577 | } 578 | } 579 | } 580 | function StartupItems 581 | { 582 | ## 20170512.jmeyer.Gathering startup items for removal of startup items at a later revision. 583 | ## 20210813.jmeyer.Added If statement for offboarding as this step won't be needed if the client is off-boarding. 584 | if ($Optimizations -contains "Offboarding") 585 | { 586 | Write-Host "Skipping Startup Item check." 587 | } 588 | else 589 | { 590 | Write-Host "Gathering startup items..." 591 | Get-CimInstance Win32_StartupCommand | Select-Object Name, command, Location, User | Format-List | Out-File -FilePath C:\Logs\StartupItems.txt 592 | Write-Host "Completed. List saved to C:\Logs\StartupItems.txt." 593 | } 594 | } 595 | function UserCleanup 596 | { 597 | ## 20201224.jmeyer.Added Removal of Helion accounts for offboarding regardless of last login and removing other users per limitations previously outlined. 598 | ## 20190328.jmeyer.Added cleaning up user folders for users that have not logged in in over 30 days. Does not touch Helion, Special, Default User, Public, or All Users 599 | ## 20191227.jmeyer.Adjusted removal to display only usernames of users that are being deleted, as they are being deleted. This is also written in the log now. 600 | if ($Optimizations -contains "Users") 601 | { 602 | Write-Host "Cleaning up unused User profiles in Users directory (Older than 30 days)..." -ForegroundColor Yellow 603 | $UserFolders = Get-CimInstance -ClassName Win32_UserProfile | 604 | Where-Object { ($_.localpath -notlike "*helion*") -and (!$_.Special) -and (($_.LastUseTime) -lt $DaysBack) } 605 | 606 | foreach ($User in $UserFolders) 607 | { 608 | $Username = Split-Path -Path $User.LocalPath -Leaf -Resolve 609 | Write-Host = "Deleting user: $($Username)" -ForegroundColor Red 610 | $User | Remove-CimInstance 611 | } 612 | Write-Host "Completed!" -ForegroundColor Green 613 | } 614 | elseif ($Optimizations -contains "Offboarding") 615 | { 616 | Write-Host "Cleaning up unused User profiles in Users directory (Older than 30 days)..." -ForegroundColor Yellow 617 | $UserFolders = Get-CimInstance -ClassName Win32_UserProfile | Where-Object { (!$_.Special) -and (($_.LastUseTime) -lt $DaysBack) } 618 | 619 | foreach ($User in $UserFolders) 620 | { 621 | $Username = Split-Path -Path $User.LocalPath -Leaf -Resolve 622 | Write-Host = "Deleting user: $($Username)" -ForegroundColor Red 623 | $User | Remove-CimInstance 624 | } 625 | 626 | Write-Host "Removing all helion account information..." -ForegroundColor Yellow 627 | $HelionAccounts = Get-CimInstance -ClassName Win32_UserProfile | Where-Object { ($_.localpath -like "*helion*") } 628 | 629 | foreach ($Account in $HelionAccounts) 630 | { 631 | $Username = Split-Path -Path $Account.LocalPath -Leaf -Resolve 632 | Write-Host = "Deleting user: $($Username)" -ForegroundColor Red 633 | $Account | Remove-CimInstance 634 | } 635 | Write-Host "Completed!" -ForegroundColor Green 636 | } 637 | } 638 | ## 20210727.jmeyer.Adjusted $timeout variable time. 639 | function InstallRSATGPMT($Timeout = 300) 640 | { 641 | Write-Host "Starting RSAT GPO Job..." -ForegroundColor Yellow 642 | $RSATJob = Start-Job { 643 | Write-Host "Checking for RSAT: Group Policy Management Tools..." -ForegroundColor Yellow 644 | if ((Get-WindowsCapability -Name Rsat.GroupPolicy.Management.Tools* -Online).State -ne "Installed") 645 | { 646 | Write-Host "RSAT: Group Policy Management Tools are not installed." -ForegroundColor Yellow 647 | Write-Host "Installing RSAT: Group Policy Management Tools." -ForegroundColor Yellow 648 | Get-WindowsCapability -Name Rsat.GroupPolicy.Management.Tools* -Online | Add-WindowsCapability -Online 649 | ## 20200814.jmeyer.Corrected if statement for installation of GP tools. 650 | if ((Get-WindowsCapability -Name Rsat.GroupPolicy.Management.Tools* -Online).State -eq "Installed") 651 | { 652 | Write-Host "RSAT: Group Policy Management Tools are installed." -ForegroundColor Green 653 | $Env:RSATGPMT = "Installed" 654 | } 655 | else 656 | { 657 | Write-Host "RSAT: Group Policy Management Tools did not install." -ForegroundColor Red 658 | $Env:RSATGPMT = $null 659 | } 660 | } 661 | else 662 | { 663 | Write-Host "RSAT: Group Policy Management Tools are already installed." -ForegroundColor Green 664 | $Env:RSATGPMT = "Installed" 665 | } 666 | } 667 | Receive-Job $RSATJob 668 | Write-Host "Job started!" 669 | ## 20210727.jmeyer.**Move wait and GPUpdate to later in the script.** 670 | } 671 | function GPUpdate 672 | { 673 | ## 20200812.jmeyer.Rebuilt GPUpdate to a more modern approach. 674 | if ($DomainTest) 675 | { 676 | Write-Host "We are connected to the '$Env:USERDOMAIN' domain." -ForegroundColor Green 677 | if ([ref]$Env:RSATGPMT -eq "Installed") 678 | { 679 | Write-Host "Running Policy Updates, please wait..." -ForegroundColor Yellow 680 | ## Runs Group Policy Update and does NOT force a log-off. 681 | Invoke-GPUpdate 682 | Write-Host "Policy Update completed." -ForegroundColor Green 683 | } 684 | else 685 | { 686 | Write-Host "RSAT: Group Policy Management Tools are not installed." -ForegroundColor Yellow 687 | Write-Host "Unable to run GPUpdate." -ForegroundColor Yellow 688 | } 689 | } 690 | else 691 | { 692 | Write-Host "Not connected to a domain. Not running Policy Update." -ForegroundColor Yellow 693 | } 694 | } 695 | function FlushDNS 696 | { 697 | Write-Host "Flushing DNS..." -ForegroundColor Yellow; 698 | Clear-DnsClientCache 699 | Write-Host "DNS Flush completed." -ForegroundColor Green 700 | } 701 | function IECleanup 702 | { 703 | ## Function for clearing IE Cache/Cookies. 704 | ## Does NOT delete saved passwords. 705 | Write-Host "Deleting IE Cookies/cache..." -ForegroundColor Yellow 706 | function Clear-IECachedData 707 | { 708 | ## 20160418.jomeyer.Organized and added options 709 | if ($History) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 1 } 710 | if ($Cookies) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 2 } 711 | if ($TempIEFiles) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 4 } 712 | if ($OfflineTempFiles) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 8 } 713 | if ($FormData) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 16 } 714 | if ($All) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 255 } 715 | if ($AddOn) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 4096 } 716 | if ($AllplusAddOn) { RunDll32.exe InetCpl.cpl, ClearMyTracksByProcess 4351 } 717 | } 718 | do 719 | { 720 | ## Calls function to perform the action. 721 | ## 20160418.jomeyer.Clearing more cached data 722 | ## 20170126.jmeyer.Removed "AllplusAddOn". This deleted Passwords. 723 | $continue2 = $true 724 | & Clear-IECachedData -History -Cookies -TempIEFiles -OfflineTempFiles -FormData -AddOn 725 | } 726 | While ($continue2 -eq $false) 727 | Write-Host "Completed!" -ForegroundColor Green 728 | } 729 | function EdgeCleanup 730 | { 731 | ## 20210922.jmeyer.Added Microsoft Edge cleanup. 732 | Write-Host "Checking to see if Microsoft Edge is installed..." -ForegroundColor Yellow 733 | if ($Edge) 734 | { 735 | Write-Host "Deleting Microsoft Edge cache..." -ForegroundColor Yellow 736 | Remove-Item -Path "$EdgeDIR\User Data\Default\*journal" -Force -Recurse -ErrorAction SilentlyContinue 737 | #Remove-Item -Path "$EdgeDIR\User Data\Default\Cookies" -Force -Recurse -ErrorAction SilentlyContinue 738 | Remove-Item -Path "$EdgeDIR\User Data\Default\Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 739 | Remove-Item -Path "$EdgeDIR\User Data\Default\Storage\ext\*" -Force -Recurse -ErrorAction SilentlyContinue 740 | #Remove-Item -Path "$EdgeDIR\User Data\Default\Media Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 741 | Remove-Item -Path "$EdgeDIR\User Data\Default\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 742 | #Remove-Item -Path "$EdgeDIR\User Data\Default\Application Cache\Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 743 | #Remove-Item -Path "$EdgeDIR\User Data\Default\File System\*" -Force -Recurse -ErrorAction SilentlyContinue 744 | Remove-Item -Path "$EdgeDIR\User Data\Default\Service Worker\*" -Force -Recurse -ErrorAction SilentlyContinue 745 | Remove-Item -Path "$EdgeDIR\User Data\Default\JumpListIcons\*" -Force -Recurse -ErrorAction SilentlyContinue 746 | Remove-Item -Path "$EdgeDIR\User Data\Default\JumpListIconsOld\*" -Force -Recurse -ErrorAction SilentlyContinue 747 | Remove-Item -Path "$EdgeDIR\User Data\Default\Local Storage\*" -Force -Recurse -ErrorAction SilentlyContinue 748 | Remove-Item -Path "$EdgeDIR\User Data\Default\IndexedDB\*" -Force -Recurse -ErrorAction SilentlyContinue 749 | Remove-Item -Path "$EdgeDIR\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot\*" -Force -Recurse -ErrorAction SilentlyContinue 750 | Remove-Item -Path "$EdgeDIR\User Data\ShaderCache\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 751 | #Remove-Item -Path "$EdgeDIR\ShaderCache\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 752 | Write-Host "Completed!" -ForegroundColor Green 753 | } 754 | else 755 | { 756 | Write-Host "Cannot find Microsoft Edge." -ForegroundColor Red 757 | } 758 | 759 | ## 20220824.jmeyer.Added Edge optimizations. NOTE: Config files required! 760 | if ($Optimizations -contains "Edge" -or "All") 761 | { 762 | $EdgeFilePath = ".\ConfigurationFiles\EdgeSettings.json" 763 | If (Test-Path $EdgeFilePath) 764 | { 765 | Write-EventLog -EventId 80 -Message "Edge Policy Settings" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Information 766 | Write-Host "[VDI Optimize] Edge Policy Settings" -ForegroundColor Cyan 767 | $EdgeSettings = Get-Content $EdgeFilePath | ConvertFrom-Json 768 | If ($EdgeSettings.Count -gt 0) 769 | { 770 | Write-EventLog -EventId 80 -Message "Processing Edge Policy Settings ($($EdgeSettings.Count) Hives)" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Information 771 | Write-Verbose "Processing Edge Policy Settings ($($EdgeSettings.Count) Hives)" 772 | Foreach ($Key in $EdgeSettings) 773 | { 774 | If ($Key.VDIState -eq 'Enabled') 775 | { 776 | If ($key.RegItemValueName -eq 'DefaultAssociationsConfiguration') 777 | { 778 | Copy-Item .\ConfigurationFiles\DefaultAssociationsConfiguration.xml $key.RegItemValue -Force 779 | } 780 | If (Get-ItemProperty -Path $Key.RegItemPath -Name $Key.RegItemValueName -ErrorAction SilentlyContinue) 781 | { 782 | Write-EventLog -EventId 80 -Message "Found key, $($Key.RegItemPath) Name $($Key.RegItemValueName) Value $($Key.RegItemValue)" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Information 783 | Write-Verbose "Found key, $($Key.RegItemPath) Name $($Key.RegItemValueName) Value $($Key.RegItemValue)" 784 | Set-ItemProperty -Path $Key.RegItemPath -Name $Key.RegItemValueName -Value $Key.RegItemValue -Force 785 | } 786 | Else 787 | { 788 | If (Test-path $Key.RegItemPath) 789 | { 790 | Write-EventLog -EventId 80 -Message "Path found, creating new property -Path $($Key.RegItemPath) -Name $($Key.RegItemValueName) -PropertyType $($Key.RegItemValueType) -Value $($Key.RegItemValue)" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Information 791 | Write-Verbose "Path found, creating new property -Path $($Key.RegItemPath) Name $($Key.RegItemValueName) PropertyType $($Key.RegItemValueType) Value $($Key.RegItemValue)" 792 | New-ItemProperty -Path $Key.RegItemPath -Name $Key.RegItemValueName -PropertyType $Key.RegItemValueType -Value $Key.RegItemValue -Force | Out-Null 793 | } 794 | Else 795 | { 796 | Write-EventLog -EventId 80 -Message "Creating Key and Path" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Information 797 | Write-Verbose "Creating Key and Path" 798 | New-Item -Path $Key.RegItemPath -Force | New-ItemProperty -Name $Key.RegItemValueName -PropertyType $Key.RegItemValueType -Value $Key.RegItemValue -Force | Out-Null 799 | } 800 | 801 | } 802 | } 803 | } 804 | } 805 | Else 806 | { 807 | Write-EventLog -EventId 80 -Message "No Edge Policy Settings Found!" -LogName 'Virtual Desktop Optimization' -Source 'EdgeVDOT' -EntryType Warning 808 | Write-Warning "No Edge Policy Settings found" 809 | } 810 | } 811 | Else 812 | { 813 | Write-Host "Foo, nothing to do here" 814 | } 815 | } 816 | } 817 | function ChromeCleanup 818 | { 819 | ## 20160510.jomeyer.Added Chrome cleanup 820 | Write-Host "Checking to see if Chrome is installed..." -ForegroundColor Yellow 821 | if ($Chrome) 822 | { 823 | Write-Host "Chrome is installed." -ForegroundColor Green 824 | Write-Host "Deleting Chrome cache..." -ForegroundColor Yellow 825 | Remove-Item -Path "$ChromeDIR\User Data\Default\*journal" -Force -Recurse -ErrorAction SilentlyContinue 826 | Remove-Item -Path "$ChromeDIR\User Data\Default\Cookies" -Force -Recurse -ErrorAction SilentlyContinue 827 | Remove-Item -Path "$ChromeDIR\User Data\Default\Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 828 | Remove-Item -Path "$ChromeDIR\User Data\Default\Storage\ext\*" -Force -Recurse -ErrorAction SilentlyContinue 829 | Remove-Item -Path "$ChromeDIR\User Data\Default\Media Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 830 | Remove-Item -Path "$ChromeDIR\User Data\Default\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 831 | Remove-Item -Path "$ChromeDIR\User Data\Default\Application Cache\Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 832 | Remove-Item -Path "$ChromeDIR\User Data\Default\File System\*" -Force -Recurse -ErrorAction SilentlyContinue 833 | Remove-Item -Path "$ChromeDIR\User Data\Default\Service Worker\*" -Force -Recurse -ErrorAction SilentlyContinue 834 | Remove-Item -Path "$ChromeDIR\User Data\Default\JumpListIcons\*" -Force -Recurse -ErrorAction SilentlyContinue 835 | Remove-Item -Path "$ChromeDIR\User Data\Default\JumpListIconsOld\*" -Force -Recurse -ErrorAction SilentlyContinue 836 | Remove-Item -Path "$ChromeDIR\User Data\Default\Local Storage\*" -Force -Recurse -ErrorAction SilentlyContinue 837 | Remove-Item -Path "$ChromeDIR\User Data\Default\IndexedDB\*" -Force -Recurse -ErrorAction SilentlyContinue 838 | Remove-Item -Path "$ChromeDIR\User Data\Default\Pepper Data\Shockwave Flash\WritableRoot\*" -Force -Recurse -ErrorAction SilentlyContinue 839 | Remove-Item -Path "$ChromeDIR\User Data\ShaderCache\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 840 | Remove-Item -Path "$ChromeDIR\ShaderCache\GPUCache\*" -Force -Recurse -ErrorAction SilentlyContinue 841 | Write-Host "Completed!" -ForegroundColor Green 842 | } 843 | else 844 | { 845 | Write-Host "Cannot find Google Chrome." -ForegroundColor Red 846 | } 847 | } 848 | function FirefoxCleanup 849 | { 850 | ## 20161222.jmeyer.Added firefox cache removal 851 | Write-Host "Checking to see if Mozilla Firefox is installed..." -ForegroundColor Yellow 852 | if ($Firefox) 853 | { 854 | Write-Host "Mozilla Firefox is installed." -ForegroundColor Green 855 | Write-Host "Deleting Mozilla Firefox cache..." -ForegroundColor Yellow 856 | ## Remove all of Mozilla Firefox's Temporary Internet Files. 857 | Remove-Item -Path "$FirefoxDirL\\Profiles\*\cache2\entries\*" -Force -Recurse 858 | Remove-Item -Path "$FirefoxDirR\\Profiles\*\storage\default\*" -Force -Recurse 859 | Write-Host "Completed!" -ForegroundColor Green 860 | } 861 | else 862 | { 863 | Write-Host "Cannot find Mozilla Firefox." -ForegroundColor Red 864 | } 865 | } 866 | ## 20220824.jmeyer.Disable and remove Windows Media Player 867 | function WindowsMediaPlayer 868 | { 869 | If ($Optimizations -contains "WindowsMediaPlayer" -or "All") 870 | { 871 | try 872 | { 873 | Write-EventLog -EventId 10 -Message "[VDI Optimize] Disable / Remove Windows Media Player" -LogName 'Virtual Desktop Optimization' -Source 'WindowsMediaPlayer' -EntryType Information 874 | Write-Host "[VDI Optimize] Disable / Remove Windows Media Player" -ForegroundColor Cyan 875 | Disable-WindowsOptionalFeature -Online -FeatureName WindowsMediaPlayer -NoRestart | Out-Null 876 | Get-WindowsPackage -Online -PackageName "*Windows-mediaplayer*" | ForEach-Object { 877 | Write-EventLog -EventId 10 -Message "Removing $($_.PackageName)" -LogName 'Virtual Desktop Optimization' -Source 'WindowsMediaPlayer' -EntryType Information 878 | Remove-WindowsPackage -PackageName $_.PackageName -Online -ErrorAction SilentlyContinue -NoRestart | Out-Null 879 | } 880 | } 881 | catch 882 | { 883 | Write-EventLog -EventId 110 -Message "Disabling / Removing Windows Media Player - $($_.Exception.Message)" -LogName 'Virtual Desktop Optimization' -Source 'WindowsMediaPlayer' -EntryType Error 884 | } 885 | } 886 | } 887 | ## 20220824.jmeyer.Remove Appx Packages. NOTE: Config files required! 888 | function AppxPackages 889 | { 890 | If ($Optimizations -contains "AppxPackages" -or "All") 891 | { 892 | $AppxConfigFilePath = ".\ConfigurationFiles\AppxPackages.json" 893 | If (Test-Path $AppxConfigFilePath) 894 | { 895 | Write-EventLog -EventId 20 -Message "[VDI Optimize] Removing Appx Packages" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Information 896 | Write-Host "[VDI Optimize] Removing Appx Packages" -ForegroundColor Cyan 897 | $AppxPackage = (Get-Content $AppxConfigFilePath | ConvertFrom-Json).Where({ $_.VDIState -eq 'Disabled' }) 898 | If ($AppxPackage.Count -gt 0) 899 | { 900 | Foreach ($Item in $AppxPackage) 901 | { 902 | try 903 | { 904 | Write-EventLog -EventId 20 -Message "Removing Provisioned Package $($Item.AppxPackage)" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Information 905 | Write-Verbose "Removing Provisioned Package $($Item.AppxPackage)" 906 | Get-AppxProvisionedPackage -Online | Where-Object { $_.PackageName -like ("*{0}*" -f $Item.AppxPackage) } | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue | Out-Null 907 | 908 | Write-EventLog -EventId 20 -Message "Attempting to remove [All Users] $($Item.AppxPackage) - $($Item.Description)" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Information 909 | Write-Verbose "Attempting to remove [All Users] $($Item.AppxPackage) - $($Item.Description)" 910 | Get-AppxPackage -AllUsers -Name ("*{0}*" -f $Item.AppxPackage) | Remove-AppxPackage -AllUsers -ErrorAction SilentlyContinue 911 | 912 | Write-EventLog -EventId 20 -Message "Attempting to remove $($Item.AppxPackage) - $($Item.Description)" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Information 913 | Write-Verbose "Attempting to remove $($Item.AppxPackage) - $($Item.Description)" 914 | Get-AppxPackage -Name ("*{0}*" -f $Item.AppxPackage) | Remove-AppxPackage -ErrorAction SilentlyContinue | Out-Null 915 | } 916 | catch 917 | { 918 | Write-EventLog -EventId 120 -Message "Failed to remove Appx Package $($Item.AppxPackage) - $($_.Exception.Message)" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Error 919 | Write-Warning "Failed to remove Appx Package $($Item.AppxPackage) - $($_.Exception.Message)" 920 | } 921 | } 922 | } 923 | Else 924 | { 925 | Write-EventLog -EventId 20 -Message "No AppxPackages found to disable" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Warning 926 | Write-Warning "No AppxPackages found to disable in $AppxConfigFilePath" 927 | } 928 | } 929 | Else 930 | { 931 | 932 | Write-EventLog -EventId 20 -Message "Configuration file not found - $AppxConfigFilePath" -LogName 'Virtual Desktop Optimization' -Source 'AppxPackages' -EntryType Warning 933 | Write-Warning "Configuration file not found - $AppxConfigFilePath" 934 | } 935 | 936 | } 937 | } 938 | ## 20220824.jmeyer.Disable Windows Traces. NOTE: Config files required! 939 | function AutoLoggers 940 | { 941 | If ($Optimizations -contains "AutoLoggers" -or "All") 942 | { 943 | $AutoLoggersFilePath = ".\ConfigurationFiles\Autologgers.Json" 944 | If (Test-Path $AutoLoggersFilePath) 945 | { 946 | Write-EventLog -EventId 50 -Message "Disable AutoLoggers" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Information 947 | Write-Host "[VDI Optimize] Disable Autologgers" -ForegroundColor Cyan 948 | $DisableAutologgers = (Get-Content $AutoLoggersFilePath | ConvertFrom-Json).Where({ $_.Disabled -eq 'True' }) 949 | If ($DisableAutologgers.count -gt 0) 950 | { 951 | Write-EventLog -EventId 50 -Message "Disable AutoLoggers" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Information 952 | Write-Verbose "Processing Autologger Configuration File" 953 | Foreach ($Item in $DisableAutologgers) 954 | { 955 | Write-EventLog -EventId 50 -Message "Updating Registry Key for: $($Item.KeyName)" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Information 956 | Write-Verbose "Updating Registry Key for: $($Item.KeyName)" 957 | Try 958 | { 959 | New-ItemProperty -Path ("{0}" -f $Item.KeyName) -Name "Start" -PropertyType "DWORD" -Value 0 -Force -ErrorAction Stop | Out-Null 960 | } 961 | Catch 962 | { 963 | Write-EventLog -EventId 150 -Message "Failed to add $($Item.KeyName)`n`n $($Error[0].Exception.Message)" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Error 964 | } 965 | 966 | } 967 | } 968 | Else 969 | { 970 | Write-EventLog -EventId 50 -Message "No Autologgers found to disable" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Warning 971 | Write-Verbose "No Autologgers found to disable" 972 | } 973 | } 974 | Else 975 | { 976 | Write-EventLog -EventId 150 -Message "File not found: $AutoLoggersFilePath" -LogName 'Virtual Desktop Optimization' -Source 'AutoLoggers' -EntryType Error 977 | Write-Warning "File Not Found: $AutoLoggersFilePath" 978 | } 979 | } 980 | } 981 | ## 20220824.jmeyer.Disable Services. NOTE: Config files required! 982 | function Services 983 | { 984 | If ($Optimizations -contains "Services" -or "All") 985 | { 986 | $ServicesFilePath = ".\ConfigurationFiles\Services.json" 987 | If (Test-Path $ServicesFilePath) 988 | { 989 | Write-EventLog -EventId 60 -Message "Disable Services" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Information 990 | Write-Host "[VDI Optimize] Disable Services" -ForegroundColor Cyan 991 | $ServicesToDisable = (Get-Content $ServicesFilePath | ConvertFrom-Json).Where({ $_.VDIState -eq 'Disabled' }) 992 | 993 | If ($ServicesToDisable.count -gt 0) 994 | { 995 | Write-EventLog -EventId 60 -Message "Processing Services Configuration File" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Information 996 | Write-Verbose "Processing Services Configuration File" 997 | Foreach ($Item in $ServicesToDisable) 998 | { 999 | Write-EventLog -EventId 60 -Message "Attempting to Stop Service $($Item.Name) - $($Item.Description)" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Information 1000 | Write-Verbose "Attempting to Stop Service $($Item.Name) - $($Item.Description)" 1001 | try 1002 | { 1003 | Stop-Service $Item.Name -Force -ErrorAction SilentlyContinue 1004 | } 1005 | catch 1006 | { 1007 | Write-EventLog -EventId 160 -Message "Failed to disable Service: $($Item.Name) `n $($_.Exception.Message)" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Error 1008 | Write-Warning "Failed to disable Service: $($Item.Name) `n $($_.Exception.Message)" 1009 | } 1010 | Write-EventLog -EventId 60 -Message "Attempting to disable Service $($Item.Name) - $($Item.Description)" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Information 1011 | Write-Verbose "Attempting to disable Service $($Item.Name) - $($Item.Description)" 1012 | Set-Service $Item.Name -StartupType Disabled 1013 | } 1014 | } 1015 | Else 1016 | { 1017 | Write-EventLog -EventId 60 -Message "No Services found to disable" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Warnnig 1018 | Write-Verbose "No Services found to disable" 1019 | } 1020 | } 1021 | Else 1022 | { 1023 | Write-EventLog -EventId 160 -Message "File not found: $ServicesFilePath" -LogName 'Virtual Desktop Optimization' -Source 'Services' -EntryType Error 1024 | Write-Warning "File not found: $ServicesFilePath" 1025 | } 1026 | } 1027 | } 1028 | ## 20220824.jmeyer.Disable Services. NOTE: Config files required! 1029 | function NetworkOptimization 1030 | { 1031 | If ($Optimizations -contains "NetworkOptimizations" -or "All") 1032 | { 1033 | $NetworkOptimizationsFilePath = ".\ConfigurationFiles\LanManWorkstation.json" 1034 | If (Test-Path $NetworkOptimizationsFilePath) 1035 | { 1036 | Write-EventLog -EventId 70 -Message "Configure LanManWorkstation Settings" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1037 | Write-Host "[VDI Optimize] Configure LanManWorkstation Settings" -ForegroundColor Cyan 1038 | $LanManSettings = Get-Content $NetworkOptimizationsFilePath | ConvertFrom-Json 1039 | If ($LanManSettings.Count -gt 0) 1040 | { 1041 | Write-EventLog -EventId 70 -Message "Processing LanManWorkstation Settings ($($LanManSettings.Count) Hives)" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1042 | Write-Verbose "Processing LanManWorkstation Settings ($($LanManSettings.Count) Hives)" 1043 | Foreach ($Hive in $LanManSettings) 1044 | { 1045 | If (Test-Path -Path $Hive.HivePath) 1046 | { 1047 | Write-EventLog -EventId 70 -Message "Found $($Hive.HivePath)" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1048 | Write-Verbose "Found $($Hive.HivePath)" 1049 | $Keys = $Hive.Keys.Where{ $_.SetProperty -eq $true } 1050 | If ($Keys.Count -gt 0) 1051 | { 1052 | Write-EventLog -EventId 70 -Message "Create / Update LanManWorkstation Keys" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1053 | Write-Verbose "Create / Update LanManWorkstation Keys" 1054 | Foreach ($Key in $Keys) 1055 | { 1056 | If (Get-ItemProperty -Path $Hive.HivePath -Name $Key.Name -ErrorAction SilentlyContinue) 1057 | { 1058 | Write-EventLog -EventId 70 -Message "Setting $($Hive.HivePath) -Name $($Key.Name) -Value $($Key.PropertyValue)" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1059 | Write-Verbose "Setting $($Hive.HivePath) -Name $($Key.Name) -Value $($Key.PropertyValue)" 1060 | Set-ItemProperty -Path $Hive.HivePath -Name $Key.Name -Value $Key.PropertyValue -Force 1061 | } 1062 | Else 1063 | { 1064 | Write-EventLog -EventId 70 -Message "New $($Hive.HivePath) -Name $($Key.Name) -Value $($Key.PropertyValue)" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1065 | Write-Host "New $($Hive.HivePath) -Name $($Key.Name) -Value $($Key.PropertyValue)" 1066 | New-ItemProperty -Path $Hive.HivePath -Name $Key.Name -PropertyType $Key.PropertyType -Value $Key.PropertyValue -Force | Out-Null 1067 | } 1068 | } 1069 | } 1070 | Else 1071 | { 1072 | Write-EventLog -EventId 70 -Message "No LanManWorkstation Keys to create / update" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Warning 1073 | Write-Warning "No LanManWorkstation Keys to create / update" 1074 | } 1075 | } 1076 | Else 1077 | { 1078 | Write-EventLog -EventId 70 -Message "Registry Path not found $($Hive.HivePath)" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Warning 1079 | Write-Warning "Registry Path not found $($Hive.HivePath)" 1080 | } 1081 | } 1082 | } 1083 | Else 1084 | { 1085 | Write-EventLog -EventId 70 -Message "No LanManWorkstation Settings foun" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Warning 1086 | Write-Warning "No LanManWorkstation Settings found" 1087 | } 1088 | } 1089 | Else 1090 | { 1091 | Write-EventLog -EventId 70 -Message "File not found - $NetworkOptimizationsFilePath" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Warning 1092 | Write-Warning "File not found - $NetworkOptimizationsFilePath" 1093 | } 1094 | 1095 | # NIC Advanced Properties performance settings for network biased environments 1096 | Write-EventLog -EventId 70 -Message "Configuring Network Adapter Buffer Size" -LogName 'Virtual Desktop Optimization' -Source 'NetworkOptimizations' -EntryType Information 1097 | Write-Host "[VDI Optimize] Configuring Network Adapter Buffer Size" -ForegroundColor Cyan 1098 | Set-NetAdapterAdvancedProperty -DisplayName "Send Buffer Size" -DisplayValue 4MB -NoRestart 1099 | <# NOTE: 1100 | Note that the above setting is for a Microsoft Hyper-V VM. You can adjust these values in your environment... 1101 | by querying in PowerShell using Get-NetAdapterAdvancedProperty, and then adjusting values using the... 1102 | Set-NetAdapterAdvancedProperty command. 1103 | #> 1104 | } 1105 | } 1106 | function UserTempFiles 1107 | { 1108 | ## Remove all files and folders in user's Temporary Internet Files. 1109 | ## 20170327.jmeyer.Added .NET Framework log file removal. 1110 | ## 20170627.jmeyer.Moved .NET log files to the System Level log files section to clean up script. 1111 | ## 20170627.jmeyer.Added temporary internet files. 1112 | Write-Host "Deleting User level Temporary Internet files..." -ForegroundColor Yellow 1113 | Remove-Item -Path "$UserDir\Local\Microsoft\Windows\Temporary Internet Files\*" -Force -Recurse -ErrorAction SilentlyContinue 1114 | Remove-Item -Path "$UserDir\Local\Microsoft\Feeds Cache\*" -Force -Recurse -ErrorAction SilentlyContinue 1115 | Remove-Item -Path "$UserDir\Local\Microsoft\Internet Explorer\DOMStore\*" -Force -Recurse -ErrorAction SilentlyContinue 1116 | Remove-Item -Path "$UserDir\Local\Microsoft\Windows\INetCache\*" -Force -Recurse -ErrorAction SilentlyContinue 1117 | Remove-Item -Path "$UserDir\Local\Packages\windows_ie_ac_001\AC\INetCache" -Force -Recurse -ErrorAction SilentlyContinue 1118 | Remove-Item -Path "$UserDir\Local\Microsoft\Internet Explorer\Recovery" -Force -Recurse -ErrorAction SilentlyContinue 1119 | Write-Host "Completed!" -ForegroundColor Green 1120 | 1121 | ## Deletes all user level Temp files. 1122 | ## 20160705.jomeyer.Added removal of ThumbNail cache, Crash Dumps, and ElevatedDiagnostics. 1123 | ## 20170627.jmeyer.Moved the below to User level Temp files section to clean up script and added program usage log files. 1124 | Write-Host "Deleting User level Temp files..." -ForegroundColor Yellow 1125 | Remove-Item -Path "$UserDir\Local\Temp\*" -Force -Recurse -ErrorAction SilentlyContinue 1126 | Remove-Item -Path "$UserDir\Roaming\Microsoft\Windows\Cookies\*.txt" -Force -Recurse -ErrorAction SilentlyContinue 1127 | Remove-Item -Path "$UserDir\Local\Microsoft\Explorer\thumb*.db" -Force -Recurse -ErrorAction SilentlyContinue 1128 | Remove-Item -Path "$UserDir\Local\CrashDumps\*" -Force -Recurse -ErrorAction SilentlyContinue 1129 | Remove-Item -Path "$UserDir\Local\ElevatedDiagnostics\*" -Force -Recurse -ErrorAction SilentlyContinue 1130 | Remove-Item -Path "$UserDir\Local\Microsoft\CLR_v4.0" -Force -Recurse -ErrorAction SilentlyContinue 1131 | Write-Host "Completed!" -ForegroundColor Green 1132 | 1133 | ## Delets all files and folders in user's Office Cache folder. 1134 | ## 20160512.jomeyer.added office cache. This is not removed when Temp Inet Files are removed. 1135 | Write-Host "Deleting User level Office Internet cache..." -ForegroundColor Yellow 1136 | Remove-Item -Path "$UserDir\Local\Microsoft\Windows\Temporary Internet Files\Content.MSO" -Force -Recurse -ErrorAction SilentlyContinue 1137 | Write-Host "Completed!" -ForegroundColor Green 1138 | 1139 | ## 20170127.jmeyer.Moved Outlook cache clearing together. Easier to track items in the script. 1140 | ## Delets all files and folders in user's Outlook cache folder. 1141 | ## 20160512.jomeyer.added Outlook cache. Temp Inet Files are already cleaned up, this is included in that. 1142 | Write-Host "Deleting User level Outlook Internet cache..." -ForegroundColor Yellow 1143 | Remove-Item -Path "$UserDir\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook" -Force -Recurse -ErrorAction SilentlyContinue 1144 | Write-Host "Completed!" -ForegroundColor Green 1145 | 1146 | ## 20170127.jmeyer.Removed deletion of Recent documents history. 1147 | 1148 | ## Delets all files and folders in user's Word cache folder. 1149 | ## 20160512.jomeyer.added office cache. This is not removed when Temp Inet Files are removed. 1150 | Write-Host "Deleting User level Word Internet cache..." -ForegroundColor Yellow 1151 | Remove-Item -Path "$UserDir\Local\Microsoft\Windows\Temporary Internet Files\Content.Word" -Force -Recurse -ErrorAction SilentlyContinue 1152 | Write-Host "Completed!" -ForegroundColor Green 1153 | 1154 | ## Delets all files and folders in user's InfoPath Cache folder. 1155 | ## 20160419.jomeyer.No longer remove directory, only remove files in the directory. 1156 | Write-Host "Deleting User level InfoPath cache..." -ForegroundColor Yellow 1157 | Remove-Item -Path "$UserDir\Local\Microsoft\InfoPath\*" -Force -Recurse -ErrorAction SilentlyContinue 1158 | Write-Host "Completed!" -ForegroundColor Green 1159 | } 1160 | function JavaCache 1161 | { 1162 | ## 20160728.jomeyer.Added Java cache. 1163 | Write-Host "Checking for User level Java Cache..." -ForegroundColor Yellow 1164 | if ($JavaCacheTest) 1165 | { 1166 | Write-Host "Java Cache Found!" -ForegroundColor Green 1167 | Write-host "Deleting Java Cache..." -ForegroundColor Yellow 1168 | Remove-Item -Path "$UserDir\LocalLow\Sun\Java\Deployment\cache\*" -Force -Recurse 1169 | Write-Host "Completed!" -ForegroundColor Green 1170 | } 1171 | else 1172 | { 1173 | Write-Host "No Java Cache found." -ForegroundColor Red 1174 | } 1175 | } 1176 | function AdobeAcrobat 1177 | { 1178 | ## 20161109.jmeyer.Added Adobe cache check. 1179 | ## 20161226.jmeyer.Added Adobe Acrobat Standard/Pro cache. 1180 | Write-Host "Checking for User level Adobe Cache..." -ForegroundColor Yellow 1181 | if ($AdobeReaderCacheTest -or $AdobeAcrobatCacheTest) 1182 | { 1183 | if ((Test-Path "$UserDir\Local\Adobe\Acrobat\") -eq $true) 1184 | { 1185 | Write-Host "Adobe Reader Cache found..." -ForegroundColor Green 1186 | Write-Host "Removing Adobe Cache..." -ForegroundColor Yellow 1187 | Remove-Item -Path "$UserDir\Local\Adobe\Acrobat\*.lst" -Force -Recurse 1188 | Remove-Item -Path "$UserDir\Roaming\Adobe\Acrobat\DC\Cache\*.lst" -Force -Recurse 1189 | Write-Host "Completed!" -ForegroundColor Green 1190 | } 1191 | 1192 | if ((Test-Path "$UserDir\Roaming\Adobe\Acrobat\Distiller*\") -eq $true) 1193 | { 1194 | Write-Host "Adobe Acrobat cache found..." -ForegroundColor Green 1195 | Write-Host "Removing Adobe Acrobat..." -ForegroundColor Yellow 1196 | Remove-Item -Path "$UserDir\Roaming\Adobe\Acrobat\Distiller*\Cache\*" -Force -Recurse 1197 | Write-Host "Completed!" -ForegroundColor Green 1198 | } 1199 | } 1200 | else 1201 | { 1202 | Write-Host "No Adobe Cache found." -ForegroundColor Red 1203 | } 1204 | } 1205 | function AdobeFlash 1206 | { 1207 | ## 20170327.jmeyer.Added Flash Player cache removal. 1208 | Write-Host "Checking for User level Flash Player cache..." -ForegroundColor Yellow 1209 | if ($AdobeFlashCacheTest) 1210 | { 1211 | Write-Host "Adobe Flash Player cache found..." -ForegroundColor Green 1212 | Write-Host "Removing Flash Player cache..." -ForegroundColor Yellow 1213 | Remove-Item -Path "$UserDir\Roaming\Macromedia\Flash Player\*.sol" -Force -Recurse 1214 | Write-Host "Completed!" -ForegroundColor Green 1215 | } 1216 | else 1217 | { 1218 | Write-Host "No Adobe Flash Player cache found." -ForegroundColor Red 1219 | } 1220 | } 1221 | function OfficeCleanup 1222 | { 1223 | ## 20160512.jomeyer.Added removal of Office cache. 1224 | ## 20160707.jomeyer.Office 2010/13/16 cache locations. 1225 | Write-Host "Checking for Microsoft Office Cache..." -ForegroundColor Yellow 1226 | if ($Office10) 1227 | { 1228 | ## 20160707.jomeyer.Office 2010 cache. 1229 | Write-Host "Deleting User level Office 2010 file cache..." -ForegroundColor Yellow 1230 | Remove-Item -Path "$UserDir\$OfficeDir\14.0\OfficeFileCache\*" -Force -Recurse 1231 | Write-Host "Completed!" -ForegroundColor Green 1232 | } 1233 | else 1234 | { 1235 | Write-Host "No Office 2010 file cache found." -ForegroundColor Red 1236 | } 1237 | 1238 | if ($Office13) 1239 | { 1240 | ## 20160707.jomeyer.Office 2013 cache. 1241 | Write-Host "Deleting User level Office 2013 file cache..." -ForegroundColor Yellow 1242 | Remove-Item -Path "$UserDir\$OfficeDir\15.0\OfficeFileCache\*" -Force -Recurse 1243 | Write-Host "Completed!" -ForegroundColor Green 1244 | } 1245 | else 1246 | { 1247 | Write-Host "No Office 2013 file cache found." -ForegroundColor Red 1248 | } 1249 | 1250 | if ($Office16) 1251 | { 1252 | ## 20160707.jomeyer.Office 2016 cache. 1253 | Write-Host "Deleting User level Office 2016 file cache..." -ForegroundColor Yellow 1254 | Remove-Item -Path "$UserDir\$OfficeDir\16.0\OfficeFileCache\*" -Force -Recurse 1255 | Write-Host "Completed!" -ForegroundColor Green 1256 | } 1257 | else 1258 | { 1259 | Write-Host "No Office 2016 file cache found." -ForegroundColor Red 1260 | } 1261 | } 1262 | ## 20220824.jmeyer.Combined SystemTempFiles and SystemLogFiles together in the same function to simplify script. 1263 | function SystemFiles 1264 | { 1265 | ## Removes all files in the Windows Temp folder. 1266 | Write-Host "Removing System level Temp files..." -ForegroundColor Yellow 1267 | Remove-Item -Path $env:TEMP\* -Force -Recurse -ErrorAction SilentlyContinue 1268 | Write-Host "Completed." -ForegroundColor Green 1269 | 1270 | ## 20160706.jomeyer.Added prefetch data. 1271 | Write-Host "Removing System level Prefetch Data..." -ForegroundColor Yellow 1272 | Remove-Item -Path C:\Windows\Prefetch\*.pf -Force -Recurse -ErrorAction SilentlyContinue 1273 | Write-Host "Completed." -ForegroundColor Green 1274 | 1275 | ## 20161223.jmeyer.Added FontCache. 1276 | Write-Host "Removing System level FontCache..." -ForegroundColor Yellow 1277 | Remove-Item C:\Windows\ServiceProfiles\LocalService\AppData\Local\FontCache* -Force -Recurse -ErrorAction SilentlyContinue 1278 | Write-Host "Completed." -ForegroundColor Green 1279 | 1280 | ## 20220824.jmeyer.Combining several type of files and removing regardless of directory. 1281 | Write-Host "Removing .tmp, .etl, .evtx, thumbcache*.db, *.log files not in use" -ForegroundColor Yellow 1282 | Get-ChildItem -Path C:\ -Include *.tmp, *.dmp, *.etl, *.evtx, thumbcache*.db, *.log -File -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -ErrorAction SilentlyContinue 1283 | Write-Host "Completed." -ForegroundColor Green 1284 | 1285 | ## 20170627.jmeyer.Added more log files and moved .NET log files to this section. 1286 | ## 20170125.jmeyer.Added Windows Log file removal. Several machines shows several GB of log data. 1287 | Write-Host "Removing System level log files..." -ForegroundColor Yellow 1288 | Remove-Item -Path $env:windir\Logs\CBS\*.log -Force -Recurse -ErrorAction SilentlyContinue 1289 | Remove-Item -Path $env:windir\Microsoft.NET\Framework\*.log -Force -Recurse -ErrorAction SilentlyContinue 1290 | Remove-Item -Path $env:windir\Microsoft.NET\Framework64\*.log -Force -Recurse -ErrorAction SilentlyContinue 1291 | Remove-Item -Path $env:windir\Microsoft.NET\Framework64\*.log -Force -Recurse -ErrorAction SilentlyContinue 1292 | Remove-Item -Path $env:windir\Performance\WinSAT\*.log -Force -Recurse -ErrorAction SilentlyContinue 1293 | Remove-Item -Path $env:windir\Panther\UnattendGC\*.log -Force -Recurse -ErrorAction SilentlyContinue 1294 | Remove-Item -Path $env:windir\system32\config\systemprofile\AppData\Local\Microsoft\CLR_v4.0\UsageLogs\ -Force -Recurse -ErrorAction SilentlyContinue 1295 | Remove-Item -Path $env:windir\SysWOW64\config\systemprofile\AppData\Local\Microsoft\CLR_v4.0_32\UsageLogs\ -Force -Recurse -ErrorAction SilentlyContinue 1296 | ## 20220824.jmeyer.Expanding on removal of WER report archives 1297 | Remove-Item -Path $env:ProgramData\Microsoft\Windows\WER\Temp\* -Recurse -Force -ErrorAction SilentlyContinue 1298 | Remove-Item -Path $env:ProgramData\Microsoft\Windows\WER\ReportArchive\* -Recurse -Force -ErrorAction SilentlyContinue 1299 | Remove-Item -Path $env:ProgramData\Microsoft\Windows\WER\ReportQueue\* -Recurse -Force -ErrorAction SilentlyContinue 1300 | 1301 | Clear-BCCache -Force -ErrorAction SilentlyContinue 1302 | 1303 | Write-Host "Completed!" -ForegroundColor Green 1304 | } 1305 | function CleanIISLogFiles 1306 | { 1307 | ## 20200812.jmeyer.Added cleanup of IIS Log files that are 14 days old or older. 1308 | $IISFilePath = "C:\inetpub\logs" 1309 | $14DaysBack = (Get-Date).AddDays(-14) 1310 | $IISLog = "C:\Logs\IISLogs.txt" 1311 | $ItemsToDelete = Get-ChildItem $IISFilePath -Recurse -File *.log | Where-Object { $_.LastWriteTime -lt $14DaysBack } 1312 | 1313 | Write-Host "Cheacking for IIS Log files..." -ForegroundColor Yellow 1314 | if ($ItemsToDelete.Count -gt 0) 1315 | { 1316 | ForEach ($Item in $ItemsToDelete) 1317 | { 1318 | Write-Host "$($Item.BaseName) is older than $14DaysBack and will be deleted" | Add-Content $IISLog 1319 | Get-item $Item | Remove-Item -Verbose -Force -ErrorAction SilentlyContinue 1320 | } 1321 | } 1322 | else 1323 | { 1324 | Write-Host "No items to be deleted today (Get-Date).DateTime" | Add-Content $IISLog 1325 | } 1326 | Write-Output "Cleanup of log files older than $14DaysBack completed..." 1327 | } 1328 | function HelionUSMT 1329 | { 1330 | ## 20190603.jmeyer.Removing USMT folder if it exists. 1331 | Write-Host "Checking for Helion USMT folder..." -ForegroundColor Yellow 1332 | if ($HelionUSMT) 1333 | { 1334 | Write-Host "Found Helion USMT folder. Deleting..." -ForegroundColor Green 1335 | Remove-Item C:\temp\helion_usmt -Recurse -Force 1336 | Write-Host "Completed!" -ForegroundColor Green 1337 | } 1338 | else 1339 | { 1340 | Write-Host "No Helion USMT folder found. Continuing..." -ForegroundColor Yellow 1341 | } 1342 | } 1343 | function CleanCTemp 1344 | { 1345 | ## 20200811.jmeyer.Added cleanup of C:\Temp if over 500MB and older than 30 days old. 1346 | ## 20230130.jmeyer.Added cleanup of C:\Temp if over 100MB and older than 30 days old. 1347 | Write-Host "Checking for folder: $CTempPath" -ForegroundColor Yellow 1348 | if ($CTempTest) 1349 | { 1350 | Write-Host "Found folder: $CTempPath" -ForegroundColor Green 1351 | if ($Optimizations -contains "Offboarding") 1352 | { 1353 | Remove-Item -LiteralPath $CTempPath -Force -Recurse 1354 | } 1355 | else 1356 | { 1357 | Write-Host "Checking folder size..." -ForegroundColor Yellow 1358 | if ($CTempSize -ge .1) 1359 | { 1360 | Write-Host "Folder is $CTempSize GB. Deleting files older than $DaysBack days old." -ForegroundColor Yellow 1361 | Get-ChildItem -Path $CTempPath | Where-Object { $_.LastWriteTime -lt $DaysBack } | Remove-Item -Force -Recurse 1362 | Write-Host "Completed!" -ForegroundColor Green 1363 | } 1364 | else 1365 | { 1366 | Write-Host "Folder is not large enough to delete. Continuing..." -ForegroundColor Yellow 1367 | } 1368 | } 1369 | } 1370 | else 1371 | { 1372 | Write-Host "Folder not found. Continuing..." -ForegroundColor Green 1373 | } 1374 | } 1375 | function ClearRecycleBin 1376 | { 1377 | ## 20201205.jmeyer.Added clearing the Recylce Bin for all users. 1378 | Write-Host "Clearing the Recycle Bin..." -ForegroundColor Yellow 1379 | Clear-RecycleBin -DriveLetter C -Force 1380 | Write-Host "Completed!" -ForegroundColor Green 1381 | } 1382 | ## 20201226.jmeyer.Added removal of items in the Kaseya Patch folder that are older than 6 months. 1383 | function KaseyaPatchCleanu 1384 | { 1385 | Write-Host "Removing items in the Kaseya Patch folder that are older than 6 months..." -ForegroundColor Yellow 1386 | Get-ChildItem -Path $KPatchPath | Where-Object { $_.LastWriteTime -lt $KaseyaPatchDays } | Remove-Item -Force -Recurse 1387 | Write-Host "Completed!" -ForegroundColor Green 1388 | } 1389 | function InstallCMTrace 1390 | { 1391 | ## 20220126.jmeyer.CMTrace download has been removed by Microsoft and is no longer available. Disabling function. 1392 | 1393 | ## 20191227.jmeyer.Installing CMTrace for log viewing. 1394 | ## 20210322.jmeyer.Added try/catch to BITS due to random errors starting BITS. Added if statement to installation if download fails. 1395 | if ($PSVersionTable.PSVersion.Major -ge 3) 1396 | { 1397 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Checking for CMTrace." -Category 1 -RawData 10, 20 1398 | if ($Architecture -eq "64-bit") 1399 | { 1400 | $CMTraceInstalled = Test-Path "C:\Program Files (x86)\ConfigMgr 2012 Toolkit R2\ClientTools\CMTrace.exe" 1401 | } 1402 | else 1403 | { 1404 | $CMTraceInstalled = Test-Path "C:\Program Files\ConfigMgr 2012 Toolkit R2\ClientTools\CMTrace.exe" 1405 | } 1406 | 1407 | 1408 | if ($CMTraceInstalled) 1409 | { 1410 | Write-Host "CMTrace is installed. Continuing..." -ForegroundColor Green 1411 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "CMTrace is already installed." -Category 1 -RawData 10, 20 1412 | } 1413 | else 1414 | { 1415 | Write-Host "Installing CMTrace Log Viewer..." 1416 | $CMtraceDL = "https://download.microsoft.com/download/5/0/8/508918E1-3627-4383-B7D8-AA07B3490D21/ConfigMgrTools.msi" 1417 | $CMTrace = "C:\Temp\ConfigMgrTools.msi" 1418 | try 1419 | { 1420 | Start-BitsTransfer -Source $CMtraceDL -Destination $CMTrace -ErrorAction Stop 1421 | } 1422 | catch 1423 | { 1424 | Write-Host "CMTrace didn't download. Unable to install." -ForegroundColor Yellow 1425 | $error[0].Exception.Message 1426 | } 1427 | 1428 | if ((Test-Path $CMTrace)) 1429 | { 1430 | try 1431 | { 1432 | Start-Process $CMTrace -ArgumentList '/Quiet' -Wait 1433 | } 1434 | catch 1435 | { 1436 | Write-Warning "CMTrace did not install correctly!" 1437 | $error[0].Exception.Message 1438 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "CMTrace failed to install." -Category 1 -RawData 10, 20 1439 | } 1440 | 1441 | if ($Architecture -eq "64-bit") 1442 | { 1443 | $CMTraceInstalled = Test-Path "C:\Program Files (x86)\ConfigMgr 2012 Toolkit R2\ClientTools\CMTrace.exe" 1444 | } 1445 | else 1446 | { 1447 | $CMTraceInstalled = Test-Path "C:\Program Files\ConfigMgr 2012 Toolkit R2\ClientTools\CMTrace.exe" 1448 | } 1449 | 1450 | if ($CMTraceInstalled) 1451 | { 1452 | Write-Host "CMTrace installed! Continuing..." -ForegroundColor Green 1453 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "CMTrace installed successfully." -Category 1 -RawData 10, 20 1454 | } 1455 | else 1456 | { 1457 | Write-Host "CMTrace did not install correctly!" -ForegroundColor Yellow 1458 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "CMTrace failed to install." -Category 1 -RawData 10, 20 1459 | } 1460 | 1461 | Remove-Item $CMTrace -Force 1462 | } 1463 | } 1464 | } 1465 | } 1466 | function SFC 1467 | { 1468 | if ($Optimizations -contains "SFC") 1469 | { 1470 | Write-Host "Starting System File Checker..." -ForegroundColor Yellow 1471 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Performing SFC Scan." -Category 1 -RawData 10, 20 1472 | SFC /SCANNOW 1473 | } 1474 | } 1475 | ## 20220531.jmeyer.Added DISM Component Cleanup. 1476 | function DISM 1477 | { 1478 | if ($Optimizations -contains "DISM") 1479 | { 1480 | Write-Host "Starting Deployment Image Servicing and Management (DISM) with Restore Health..." -ForegroundColor Yellow 1481 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Performing DISM with Restore Health." -Category 1 -RawData 10, 20 1482 | ## This attempts to locate corruption or missing components and attemps to repair them. 1483 | DISM /online /Cleanup-Image /RestoreHealth 1484 | Write-Host "Starting Deployment Image Servicing and Management (DISM) with Component Cleanup..." -ForegroundColor Yellow 1485 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Performing DISM with Component Cleanup." -Category 1 -RawData 10, 20 1486 | ## This cleans up the C:\Windows\WinSxS folder properly. 1487 | DISM /online /Cleanup-Image /StartComponentCleanup /ResetBase 1488 | } 1489 | } 1490 | function DiskCleanupCheck 1491 | { 1492 | ## 20160513.jomeyer.Moved Disk Cleanup wait/check to the end of the script to speed up the overall process. 1493 | ## 20160807.jomeyer.No longer has a 20 second delay when checking for Disk Cleanup. 1494 | ## 20170127.jmeyer.Added color to the Disk Cleanup host notifications. 1495 | ## 20170620.jmeyer.Moved re-start of wuauserv to the end. 1496 | Write-Host "Checking to see if Disk Cleanup is running..." -ForegroundColor Yellow 1497 | if ([bool](Get-Process cleanmgr) -eq $true) 1498 | { 1499 | Write-Host "Disk Cleanup is running." -ForegroundColor Yellow 1500 | do 1501 | { 1502 | Write-Host "waiting for Disk Cleanup..." -ForegroundColor Yellow 1503 | Start-Sleep 16 1504 | } 1505 | while ((Get-CimInstance win32_process | Where-Object { $_.processname -eq 'cleanmgr.exe' } | Measure-Object).count) 1506 | Write-Host "Disk Cleanup has completed." -ForegroundColor Green 1507 | ## Restarts the Windows Update service. 1508 | Get-Service -Name wuauserv | Start-Service -Verbose 1509 | ## BITS will restart automatically when needed. 1510 | Write-Host "Gathering HDD information..." -ForegroundColor Yellow 1511 | } 1512 | else 1513 | { 1514 | Write-Host "Disk Cleanup is not running, continuing." -ForegroundColor Yellow 1515 | ## Restarts the Windows Update service. 1516 | Get-Service -Name wuauserv | Start-Service -Verbose 1517 | ## BITS will restart automatically when needed. 1518 | Write-Host "Gathering HDD information..." -ForegroundColor Yellow 1519 | } 1520 | } 1521 | function DiskSpaceAfter 1522 | { 1523 | ## Gather HDD size and free space after cleaning. Used for ticketing purposes. 1524 | $Env:After = Get-CimInstance Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | 1525 | Select-Object SystemName, 1526 | @{ Name = "Drive"; Expression = { ($_.DeviceID) } }, 1527 | @{ Name = "Size (GB)"; Expression = { "{0:N1}" -f ($_.Size / 1GB) } }, 1528 | @{ Name = "FreeSpace (GB)"; Expression = { "{0:N1}" -f ($_.Freespace / 1GB) } }, 1529 | @{ Name = "PercentFree"; Expression = { "{0:P1}" -f ($_.FreeSpace / $_.Size) } } | 1530 | Format-Table -AutoSize | Out-String 1531 | 1532 | $Env:Size = Get-ChildItem C:\Users\* -Include *.iso, *.vhd -Recurse | Sort-Object Length -Descending | 1533 | Select-Object Name, Directory, @{ Name = "Size (GB)"; Expression = { "{0:N2}" -f ($_.Length / 1GB) } } | 1534 | Format-Table -AutoSize | Out-String 1535 | $Env:FSpaceAfter = (Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace / 1GB 1536 | 1537 | ## 20210707.jmeyer.Adjusted variables for space reporting. 1538 | $Math = ($Env:FSpaceAfter - $Env:FSpaceBefore) 1539 | $env:SpaceSaved = [math]::Round($Math, 2) 1540 | Write-Host "Completed!" -ForegroundColor Green 1541 | ## Finished gathering space information 1542 | } 1543 | ## jmeyer.20210210.Renamed function from Housecleaning to Reporting 1544 | function Reporting 1545 | { 1546 | # Sends some before and after info for ticketing purposes 1547 | Write-Host "Before: $Env:Before" -ForegroundColor Cyan 1548 | Write-Host "After: $Env:After" -ForegroundColor Cyan 1549 | Write-Host "$Env:Size" -ForegroundColor Cyan 1550 | Write-Host "We have cleaned up $($Env:SpaceSaved)GB of space." -ForegroundColor Green 1551 | # 20170426.jmeyer.Cleaned up time reporting. 1552 | $TotalTime = (New-TimeSpan -Start $StartDate -End (Get-Date).ToShortTimeString()).TotalMinutes 1553 | Write-Host "Total time for cleanup was $TotalTime minutes." -ForegroundColor Green 1554 | } 1555 | function WorkstationRestart 1556 | { 1557 | ## 20201204.jmeyer.Removing restart/logoff option if running for offboarding. 1558 | if ($Optimizations -notcontains "Offboarding") 1559 | { 1560 | ## 20160728.jomeyer.Added option for restart or logout. Logout is required. 1561 | $title = "Helion Service Desk" 1562 | $message = "A restart is recommended but a logout is required. Please choose an option below." 1563 | $Restart = New-Object System.Management.Automation.Host.ChoiceDescription "&Restart.", "Restarts computer." 1564 | $Logout = New-Object System.Management.Automation.Host.ChoiceDescription "&Logout.", "Logs out." 1565 | $options = [System.Management.Automation.Host.ChoiceDescription[]]($Restart, $Logout) 1566 | $result = $host.ui.PromptForChoice($title, $message, $options, 1) 1567 | switch ($result) 1568 | { 1569 | 0 { $Choice = $true } 1570 | 1 { $Choice = $false } 1571 | } 1572 | if ($Choice -eq $true) 1573 | { 1574 | Write-Warning "A restart will commence automatically in 10 seconds." 1575 | Start-Sleep -Seconds $timeBeforeStart 1576 | $waitSeconds .. 1 | Foreach-Object ` 1577 | { 1578 | Write-Host "Time Remaining: $_" -ForegroundColor Yellow 1579 | Start-Sleep -Seconds 1 1580 | } 1581 | ## Restarts computer 1582 | ## 20200911.jmeyer.Removed CimInstance restart and now using native PowerShell. 1583 | ## Stops Log. 1584 | if ($PSVersionTable.PSVersion.Major -ge 3) 1585 | { 1586 | Write-Warning "Stopping log.." 1587 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "The $ScriptVersion script has ended." -Category 1 -RawData 10, 20 1588 | Stop-Transcript 1589 | } 1590 | Restart-Computer -Force -Delay 5 1591 | } 1592 | else 1593 | { 1594 | Write-Host "Please logout!" 1595 | # Write-Warning "A Logout will commence automatically in 10 seconds." 1596 | # Start-Sleep -Seconds $timeBeforeStart 1597 | # 1598 | # $waitSeconds .. 1 | Foreach-Object ` 1599 | # { 1600 | # Write-Host "Time Remaining: $_" -ForegroundColor Yellow 1601 | # Start-Sleep -Seconds 1 1602 | # } 1603 | # ## Logs out 1604 | # ## 20210325.jmeyer.Adjusted CimInstance for logout. 1605 | # Invoke-CimMethod -MethodName Win32Shutdown -ClassName Win32_OperatingSystem -Arguments @{ Flags = 4 } 1606 | } 1607 | } 1608 | } 1609 | ##20210727.jmeyer.Moved WorkstationRestart function into ScriptEnding function to simplify ending. 1610 | function ScriptEnding ($DeleteFiles) 1611 | { 1612 | Write-Host "Cleaning up..." -ForegroundColor DarkYellow 1613 | $DebugPreference = 'SilentlyContinue' 1614 | ## Removing all script files for security reasons. 1615 | Write-Host "Removing script files for security purposes..." -ForegroundColor Red 1616 | if (-not ([String]::IsNullOrEmpty($DeleteFiles))) 1617 | { 1618 | 1619 | foreach ($file in $DeleteFiles) 1620 | { 1621 | Remove-Item -Path "$DeleteFiles" -Force -Recurse -Verbose 1622 | } 1623 | } 1624 | ## Self destructs script. 1625 | Remove-Item -Path "$PSCommandPath" -Force -Verbose 1626 | Write-Host "Removing any log files that were created over $DaysBack ago..." -ForegroundColor Red 1627 | Get-ChildItem -Path "C:\Logs\$ScriptName.*" | Where-Object { $_.LastWriteTime -lt $DaysBack } | Remove-Item -Force -Recurse -Verbose 1628 | Write-Host "File deletion completed" -ForegroundColor Green 1629 | if ($ScriptIntelligence -eq "Workstation") 1630 | { 1631 | WorkstationRestart 1632 | } 1633 | ## Stops Log. 1634 | if ($PSVersionTable.PSVersion.Major -ge 3) 1635 | { 1636 | Write-Host "Stopping log..." -ForegroundColor Red 1637 | Write-EventLog -Message "The $ScriptFullName script has ended." -EventID 32701 -EntryType Information -LogName "Application" -Source "$ScriptName" -Category 1 -RawData 10, 20 1638 | Stop-Transcript 1639 | } 1640 | ## Clearing all variable content for security reasons. 1641 | Clear-Variable -Name * -Force -ErrorAction SilentlyContinue 1642 | exit 1643 | } 1644 | function ServerCleanup 1645 | { 1646 | ## 20200812.jmeyer.Server Cleanup function. 1647 | #InstallCMTrace 1648 | DiskSpaceBefore 1649 | ProcessWarning 1650 | ProcessTermination 1651 | DiskCleanup 1652 | CleanIISLogFiles 1653 | InstallRSATGPMT 1654 | FlushDNS 1655 | IECleanup 1656 | EdgeCleanup 1657 | ChromeCleanup 1658 | FirefoxCleanup 1659 | JavaCache 1660 | #KaseyaPatchCleanup 1661 | CleanCTemp 1662 | Win10UpgradeCleanup 1663 | ClearRecycleBin 1664 | DiskCleanupCheck 1665 | DiskSpaceAfter 1666 | Reporting 1667 | } 1668 | function WorkstationCleanup 1669 | { 1670 | ## 20200812.jmeyer.Workstation Cleanup function. 1671 | DiskSpaceBefore 1672 | ProcessWarning 1673 | ProcessTermination 1674 | DiskCleanup 1675 | #InstallCMTrace 1676 | InstallRSATGPMT 1677 | StartupItems 1678 | SFC 1679 | DISM 1680 | UserCleanup 1681 | FlushDNS 1682 | IECleanup 1683 | EdgeCleanup 1684 | ChromeCleanup 1685 | FirefoxCleanup 1686 | UserTempFiles 1687 | JavaCache 1688 | AdobeAcrobat 1689 | AdobeFlash 1690 | OfficeCleanup 1691 | SystemFiles 1692 | HelionUSMT 1693 | CleanCTemp 1694 | Win10UpgradeCleanup 1695 | ClearRecycleBin 1696 | GPUpdate 1697 | DiskCleanupCheck 1698 | DiskSpaceAfter 1699 | Reporting 1700 | } 1701 | ## 20170327.jmeyer.Removed all file checks.These are no longer needed as script has been reduced to a single file. 1702 | Write-Host "Setup complete!" -ForegroundColor Green 1703 | #endregion Functions 1704 | ############### 1705 | ## Variables ## 1706 | ############### 1707 | #region Variables 1708 | Write-Host "Setting Variables..." -ForegroundColor Yellow 1709 | #region Standard_Variables 1710 | ## 20170929.jmeyer.Moved to 1.6 for full deployment at Helion. 1711 | ## 20200811.jmeyer.Moved to 1.7 due to combining several scripts. 1712 | $ScriptName = "Poor_System_Performance" 1713 | $ScriptVersionNumber = "1.7.9.0" 1714 | $ScriptVersion = "$ScriptName.$ScriptVersionNumber" 1715 | $Domain = $env:USERDOMAIN 1716 | $FQDN = (Get-ADDomain).DistinguishedName 1717 | $Computer = $env:COMPUTERNAME 1718 | $OSName = (Get-CimInstance Win32_OperatingSystem).Caption 1719 | $Architecture = (Get-CimInstance Win32_OperatingSystem).OSArchitecture 1720 | $BuildNumber = (Get-CimInstance Win32_OperatingSystem).BuildNumber 1721 | $StartDate = (Get-Date).ToShortTimeString() 1722 | $DaysBack = (Get-Date).AddDays(-30) 1723 | ## 20200821.jmeyer.Added Try-Catch to the Domain Test. 1724 | try 1725 | { 1726 | $DomainTest = (Test-ComputerSecureChannel) 1727 | } 1728 | catch [System.InvalidOperationException] 1729 | { 1730 | $DomainTest = $null 1731 | } 1732 | if ($Optimizations -contains "VDI") 1733 | { 1734 | $Optimizations =+ "Edge" 1735 | } 1736 | ## GitHub Variables for AutoUpdate 1737 | $GHUserName = "OnyxXP" 1738 | ## URL's for version check and script file 1739 | $GitHubVersion = "https://raw.githubusercontent.com/$GHUserName/$($ScriptName)/main/CurrentVersion.txt" 1740 | $NewScriptFile = "https://raw.githubusercontent.com/$GHUserName/$($ScriptName)/main/$($ScriptName).ps1" 1741 | #endregion Standard_Variables 1742 | ## 20170125.jmeyer.Added all user's to cleanup. 1743 | $UserDir = "C:\Users\*\AppData" 1744 | $OfficeDir = "Local\Microsoft\Office" 1745 | $Chrome = Test-Path "$UserDir\Local\Google\Chrome" 1746 | $ChromeDIR = "$UserDir\Local\Google\Chrome" 1747 | $Edge = Test-Path "$UserDir\Local\Microsoft\Edge" 1748 | $EdgeDIR = "$UserDir\Local\Microsoft\Edge" 1749 | ## 20161222.jmeyer.Added firefox cache. 1750 | $FirefoxDirL = "$UserDir\Local\Mozilla\Firefox" 1751 | $FirefoxDirR = "$UserDir\Roaming\Mozilla\Firefox" 1752 | $Firefox = Test-Path "$UserDir\Local\Mozilla\Firefox" 1753 | $Office10 = Test-Path "$UserDir\$OfficeDir\14.0\OfficeFileCache" 1754 | $Office13 = Test-Path "$UserDir\$OfficeDir\15.0\OfficeFileCache" 1755 | $Office16 = Test-Path "$UserDir\$OfficeDir\16.0\OfficeFileCache" 1756 | $JavaCacheTest = Test-Path "$UserDir\LocalLow\Sun\Java\Deployment\cache" 1757 | $AdobeReaderCacheTest = Test-Path "$UserDir\Local\Adobe\Acrobat\" 1758 | $AdobeAcrobatCacheTest = Test-Path "$UserDir\Roaming\Adobe\Acrobat\Distiller*\" 1759 | $AdobeFlashCacheTest = Test-Path "$UserDir\Roaming\Macromedia\Flash Player\" 1760 | ## 20200814.jmeyer.Added Helion USMT and Windows 10 Upgrade file removals. 1761 | $HelionUSMT = Test-Path C:\temp\helion_usmt 1762 | $Windows10Upgrade = Test-Path C:\Windows10Upgrade 1763 | $Win10Upgrade = Test-Path C:\Win10Upgrade 1764 | $O365Install = Test-Path C:\O365Install 1765 | $ServerWin10Upgrade = (Get-CimInstance Win32_Share | Where-Object { $_.Name -like 'Win10Upgrade$' }).Path 1766 | $ServerO365Install = (Get-CimInstance Win32_Share | Where-Object { $_.Name -like 'O365Install$' }).Path 1767 | $TimeBeforeStart = 2 1768 | $WaitSeconds = 10 1769 | ## 20180702.jmeyer.Added Firefox. 1770 | ## 20230201.jmeyer.Added Edge. 1771 | $ProcessList = "iexplorer", "msedge", "chrome", "MSACCESS", "EXCEL", "INFOPATH", "ONENOTE", "OUTLOOK", "POWERPNT", "MSPUB", "WINWORD" 1772 | $ProcessArray = @("iexplorer", "msedge", "chrome", "MSACCESS", "EXCEL", "INFOPATH", "ONENOTE", "OUTLOOK", "POWERPNT", "MSPUB", "WINWORD") 1773 | $VName = "StateFlags0032" 1774 | $DirPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches" 1775 | ## 20160419.jomeyer.removed System error minidump files 1776 | ## 20160430.jomeyer.Removed Windows 8 and XP options. These are obsolete. 1777 | ## 20210322.jmeyer.Removed options that are no longer available in Windows 10. 1778 | $TempFolders = @("Active Setup Temp Folders", "Content Indexer Cleaner", "D3D Shader Cache", "Delivery Optimization Files", "Downloaded Program Files", 1779 | "Internet Cache Files", "Offline Pages Files", "Old ChkDsk Files", "Previous Installations", "Recycle Bin", "RetailDemo Offline Content", 1780 | "Setup Log Files", "System error memory dump files", "System error minidump files", "Temporary Files", "Temporary Setup Files", 1781 | "Temporary Sync Files", "Thumbnail Cache", "Update Cleanup", "Upgrade Discarded Files", "Windows Defender", "Windows Error Reporting Files", 1782 | "Windows ESD installation files". "Windows Reset Log Files", "Windows Upgrade Log Files") 1783 | ## 20200814.jmeyer.Added C:\Temp file and Kaseya temp file removals. 1784 | $CTempPath = "C:\Temp" 1785 | $CTempTest = Test-Path "C:\Temp" 1786 | $CTempSize = (Get-ChildItem -Path $CTempPath | Measure-Object -Sum Length).Sum /1GB 1787 | $KPatchPath = 1788 | $KaseyaPatchDays = (Get-Date).AddDays(-180) 1789 | $FreeSpace = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | Where-Object DeviceID -eq 'C:' | Select-Object @{ L = "FreeSpace"; E = { $_.FreeSpace/1GB } }, @{ L = "TotalSize"; E = { $_.Size/1GB } } 1790 | $PercentFree = ($FreeSpace.FreeSpace/$FreeSpace.TotalSize) * 100 1791 | $PercentRequired = 20.0 1792 | ## Script support files to remove after completion. 1793 | $OptimizationsZip = "$PSScriptRoot\Config.zip" 1794 | $FilesToDelete = @($OptimizationsZip) 1795 | Write-Host "Finished setting up variables." -ForegroundColor Green 1796 | #endregion Variables 1797 | ########### 1798 | ## Setup ## 1799 | ########### 1800 | #region InitialSetup 1801 | InitialSetup 1802 | #endregion InitialSetup 1803 | ############################# 1804 | ## Administrator Elevation ## 1805 | ############################# 1806 | #region AdminElevation 1807 | AdminElevation 1808 | #endregion AdminElevation 1809 | ############# 1810 | ## Logging ## 1811 | ############# 1812 | #region Logging 1813 | Logging 1814 | #endregion Logging 1815 | ################ 1816 | ## AutoUpdate ## 1817 | ################ 1818 | #region AutoUpdate 1819 | AutoUpdate 1820 | #endregion AutoUpdate 1821 | ################### 1822 | ## Prerequisites ## 1823 | ################### 1824 | #region Prerequisites 1825 | Write-Host "Checking Prerequisites..." -ForegroundColor Yellow 1826 | Prerequisites 1827 | #endregion Prerequisites 1828 | ############# 1829 | ## ACTIONS ## 1830 | ############# 1831 | #region ACTIONS 1832 | Write-Host "Beginning cleanup..." -ForegroundColor Green 1833 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Beginning cleanup." -Category 1 -RawData 10, 20 1834 | 1835 | Write-Host "Checking Script Intelligence variable..." -ForegroundColor Yellow 1836 | if ($ScriptIntelligence -eq "Server") 1837 | { 1838 | Write-Host "We are running on $OSName." -ForegroundColor Green 1839 | Write-Host "Running server cleanup..." -ForegroundColor Green 1840 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Cleanup configured for Servers." -Category 1 -RawData 10, 20 1841 | ## Perform cleanup. 1842 | ServerCleanup 1843 | } 1844 | elseif ($ScriptIntelligence -eq "Workstation") 1845 | { 1846 | Write-Host "We are running on $OSName." -ForegroundColor Green 1847 | Write-Host "Running workstation cleanup..." -ForegroundColor Green 1848 | Write-EventLog -LogName "Application" -Source "$ScriptName" -EventID 32701 -EntryType Information -Message "Cleanup configured for Workstations." -Category 1 -RawData 10, 20 1849 | ## Perform cleanup. 1850 | WorkstationCleanup 1851 | } 1852 | #endregion ACTIONS 1853 | ###################### 1854 | ## Ending of script ## 1855 | ###################### 1856 | #region ENDING 1857 | ScriptEnding -DeleteFiles $FilesToDelete 1858 | #endregion ENDING 1859 | ############################# 1860 | ## Do not write below here ## 1861 | ############################# -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Poor_System_Performance 2 | Generic but extensive cleanup of cookies/cache/temp files on Windows based assets (Workstation and server). 3 | 4 | Explanation of Functions: 5 | 6 | InstallCMTrace; Download and install Microsoft's CMTrace log viewing tool from SCCM. 7 | 8 | DiskSpaceBefore; Captures disk space before the script removes any files. 9 | 10 | ProcessWarning; Checks for open processes that will interfere with the script. 11 | 12 | ProcessTermination; Closes all open processes that will interfere with the script. 13 | 14 | DiskCleanup; Launches Microsoft Disk Cleanup (cleanmgr) and sets flags for all items that it's capable of cleaning. 15 | 16 | Win10UpgradeCleanup; Removes all files related to the Windows 10 Upgrade project. 17 | 18 | CleanCTemp; Checks folder size and deletes files older than 30 days old if folder is over 1GB. 19 | 20 | CleanIISLogFiles; Cleans IIS Log files older than 14 days old. 21 | 22 | StartupItems; Reports on Startup items. (IN PROGRESS) 23 | 24 | UserCleanup; Removes Users that have not logged into the computer in over 30 days. 25 | 26 | GPUpdate; Runs GPUpdate. 27 | 28 | FlushDNS; Flushes DNS. 29 | 30 | IECleanup; Removes Cookies and Cache from IE. 31 | 32 | ChromeCleanup; Removes Cookies and Cache from Chrome. 33 | 34 | FirefoxCleanup; Removes Cookies and Cache from Firefox. 35 | 36 | UserTempFiles; Removes User specific temp files. 37 | 38 | JavaCache; Removes Java cookies and cache. 39 | 40 | AdobeAcrobat; Removes Adobe Acrobat cookies and cache. 41 | 42 | AdobeFlash; Removes Adobe Flash cookies and cache. 43 | 44 | OfficeCleanup; Removes cache from Office applications. 45 | 46 | SystemTempFiles; Removes System level Temp files. 47 | 48 | SystemLogFiles; Removes System level log files (NOT Event Viewer logs). 49 | 50 | HelionUSMT; Checks for and removes the Helion USMT folder. 51 | 52 | DiskCleanupCheck; Checks to see if Disk Cleanup is running and waits for it to complete if it is. 53 | 54 | DiskSpaceAfter; Captures disk space after the script removes files. 55 | 56 | Housecleaning; Reporting on script results. 57 | 58 | ScriptEnding; Removing script files and stop logging. 59 | 60 | WorkstationRestart; Prompts for logout and restart options. 61 | --------------------------------------------------------------------------------