What This Script Does
The auto-update-chocolatey.ps1 script is the most sophisticated and feature-rich script in the Chocolatey Scripts toolkit. It provides a fully automated, intelligent update system that keeps your Chocolatey installation and all managed packages up to date while incorporating multiple layers of safety checks to ensure updates only run under appropriate conditions. This script is designed to be executed unattended, typically through a Windows Scheduled Task, making it the centerpiece of a hands-free maintenance strategy for your Windows software.
Before attempting any updates, the script performs a series of conditional checks to verify that the environment is suitable for running package updates. The first and most important of these checks is the WiFi network verification. The script compares the currently connected wireless network against a configured network name stored in config.json. This check prevents the script from downloading potentially large package updates over metered connections, mobile hotspots, or unfamiliar networks. If the current WiFi network does not match the configured name, the script logs the mismatch and exits gracefully without performing any updates.
The second conditional check verifies that the computer is connected to AC power rather than running on battery. This is particularly important for laptop users who might have the script scheduled to run overnight. Package updates can be resource-intensive, involving downloads, installations, and system modifications that consume significant CPU cycles and disk I/O. Running these operations on battery power could drain the battery unexpectedly or cause the system to shut down mid-update, potentially leaving packages in a corrupted state. The power check queries the Windows Management Instrumentation (WMI) subsystem to determine the current power source, and if the machine is running on battery, the script defers the update to the next scheduled run.
The third conditional check confirms that the script is running with Administrator privileges. While this may seem redundant for a scheduled task that should already be configured to run elevated, the check serves as a safety net. Chocolatey package installations and updates require administrator access to modify program files, registry entries, and system PATH variables. If the script somehow runs without elevation, it will fail gracefully with a clear log message rather than producing confusing permission-denied errors partway through the update process.
Once all conditional checks pass, the script proceeds to the update phase, which operates in three distinct stages. The first stage updates the Chocolatey package manager itself by running choco upgrade chocolatey. Keeping Chocolatey up to date is important because newer versions include bug fixes, performance improvements, and enhanced package handling capabilities. The second stage runs choco upgrade all to update every installed package to its latest available version. The third stage performs a cleanup of obsolete package versions and cached downloads to reclaim disk space and keep the Chocolatey installation tidy.
The update process incorporates retry logic to handle transient network failures gracefully. If a package download fails due to a network timeout or server error, the script does not immediately give up. Instead, it waits for a configurable delay period and then retries the failed operation. The maximum number of retry attempts and the delay between retries are both configurable through config.json. This retry mechanism is particularly valuable for scheduled tasks that run during off-hours when network equipment might be restarting or when internet service providers perform maintenance.
Email notification support is one of the standout features of this script. After the update process completes, whether successfully or with errors, the script can send a detailed email report to a configured address. This email includes a summary of which packages were updated, which failed, the total execution time, and any warnings or errors that occurred during the process. The email configuration supports SMTP server settings with configurable port numbers, allowing it to work with a variety of email providers and corporate mail servers. For users who prefer not to receive emails, the notification system can be disabled through config.json.
In addition to email notifications, the script integrates with the Send-ToastNotification.ps1 helper function to display Windows toast notifications. These pop-up notifications provide immediate visual feedback when the script runs interactively or when a user is logged in during a scheduled execution. The toast notifications display a brief summary of the update results, including the number of packages updated and whether any errors occurred. This dual notification approach ensures you stay informed about the state of your system regardless of whether you are actively monitoring the machine.
All operations performed by this script are logged in detail to %USERPROFILE%\Logs\AutoUpdateChocolatey.log. The log file captures the results of every conditional check, each package update attempt including retry attempts, the email notification status, and the overall execution summary. The log uses a timestamped format that makes it easy to correlate events and diagnose issues. Over time, these logs provide a complete history of your system's update activity, which is useful for troubleshooting problems or auditing software changes.
The script loads all of its configuration from a config.json file located in the same directory as the script. This centralized configuration approach means you can customize the behavior of the auto-update process without modifying the script itself. This separation of configuration from code is a deliberate design choice that makes it safe to update the script from the repository without losing your personal settings. The configuration file is validated at startup, and if any required values are missing or invalid, the script logs a helpful error message identifying exactly which configuration keys need attention.
Usage
The script can be run manually or through a scheduled task. Manual execution requires an elevated PowerShell window.
# Run manually from the scripts directory
.\auto-update-chocolatey.ps1
For automated execution, use the setup-scheduled-tasks.ps1 script to create a Windows Scheduled Task, or create one manually:
# Example: Create a scheduled task to run every Sunday at 3:00 AM
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-ExecutionPolicy Bypass -File C:\path\to\auto-update-chocolatey.ps1"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 3am
Register-ScheduledTask -TaskName "ChocolateyAutoUpdate" `
-Action $action -Trigger $trigger -RunLevel Highest
Configuration
The script reads its settings from config.json in the script directory. Below are all available configuration options.
| Key | Type | Description |
|---|---|---|
wifiNetwork | String | The SSID of the WiFi network required for updates to proceed. Set to an empty string to skip this check. |
emailAddress | String | The email address to receive update reports. Leave empty to disable email notifications. |
smtpServer | String | The SMTP server hostname for sending email notifications (e.g., smtp.gmail.com). |
smtpPort | Integer | The SMTP server port number (e.g., 587 for TLS, 465 for SSL). |
maxRetries | Integer | Maximum number of retry attempts for failed package operations. Default: 3. |
retryDelaySeconds | Integer | Seconds to wait between retry attempts. Default: 30. |
notifications.email | Boolean | Enable or disable email notification reports. Default: true. |
notifications.toast | Boolean | Enable or disable Windows toast notifications. Default: true. |
Example config.json:
{
"wifiNetwork": "MyHomeNetwork",
"emailAddress": "[email protected]",
"smtpServer": "smtp.gmail.com",
"smtpPort": 587,
"maxRetries": 3,
"retryDelaySeconds": 30,
"notifications": {
"email": true,
"toast": true
}
}
What Gets Changed
- Chocolatey upgrade — Updates the Chocolatey package manager itself to the latest version.
- Package upgrades — Updates all installed Chocolatey packages to their latest available versions.
- Cache cleanup — Removes old package versions and cached downloads after updates complete.
- Log file — Creates or appends to
%USERPROFILE%\Logs\AutoUpdateChocolatey.log. - Email notification — Sends an update report to the configured email address (if enabled).
- Toast notification — Displays a Windows notification with the update summary (if enabled).