自动提醒更新软件的脚本怎么写

wen 实用脚本 2

本文目录导读:

自动提醒更新软件的脚本怎么写

  1. Windows PowerShell 脚本(适合 Win10/Win11)
  2. macOS/Linux Shell 脚本(适合命令行环境)
  3. 脚本核心原理
  4. 进阶用法(推荐工具)

这是一个比较完整的自动检测并提醒软件更新的脚本示例,我会提供 Windows(PowerShell)macOS/Linux(Shell) 两个版本。


Windows PowerShell 脚本(适合 Win10/Win11)

这个脚本会检查几个常见软件(如 Chrome、VS Code、7-Zip)的当前版本与官方最新版本,如果发现更新则弹出系统通知。

# 文件名: check-updates.ps1
# 用法: 右键"使用 PowerShell 运行",或添加到任务计划程序
# 定义要检查的软件列表(名称 + 获取版本的方法)
$SoftwareChecks = @(
    @{
        Name = "Google Chrome"
        # 从注册表获取当前版本
        CurrentVersion = (Get-ItemProperty "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome" -ErrorAction SilentlyContinue).DisplayVersion
        # 从官方接口获取最新版本(JSON)
        LatestVersionUrl = "https://omahaproxy.appspot.com/win?channel=stable&platform=win64&json=1"
        # 解析 JSON 获取版本号的逻辑
        ParseLatestVersion = { param($json) ($json | ConvertFrom-Json).versions[0].version }
        # 下载地址
        DownloadUrl = "https://www.google.com/chrome/"
    }
    @{
        Name = "Visual Studio Code"
        CurrentVersion = (Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\{EA457F21-F9CC-448E-B435-0A0B1E5D1A7D}" -ErrorAction SilentlyContinue).DisplayVersion
        # VS Code 官方 GitHub Release API
        LatestVersionUrl = "https://api.github.com/repos/microsoft/vscode/releases/latest"
        ParseLatestVersion = { param($json) $json.tag_name -replace "^v", "" }
        DownloadUrl = "https://code.visualstudio.com/download"
    }
    @{
        Name = "7-Zip"
        CurrentVersion = (Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip" -ErrorAction SilentlyContinue).DisplayVersion
        # 7-Zip 官网页面解析(需要简单 HTML 解析)
        LatestVersionUrl = "https://www.7-zip.org/"
        ParseLatestVersion = {
            param($html)
            # 匹配类似 "Download 7-Zip 23.01" 这样的文本
            if ($html -match 'Download 7-Zip (\d+\.\d+)') {
                return $matches[1]
            }
            return $null
        }
        DownloadUrl = "https://www.7-zip.org/download.html"
    }
)
# 引入系统通知程序集
Add-Type -AssemblyName System.Windows.Forms
foreach ($app in $SoftwareChecks) {
    Write-Host "检查: $($app.Name)" -ForegroundColor Cyan
    try {
        # 获取当前版本
        $current = $app.CurrentVersion
        if (-not $current) {
            Write-Host "  ❌ 未安装或无法获取当前版本" -ForegroundColor Red
            continue
        }
        Write-Host "  当前版本: $current"
        # 获取最新版本(调用对应接口)
        $response = Invoke-RestMethod -Uri $app.LatestVersionUrl -ErrorAction Stop
        if ($app.ParseLatestVersion) {
            $latest = & $app.ParseLatestVersion $response
        } else {
            $latest = $response  # 如果直接返回版本字符串
        }
        if (-not $latest) {
            Write-Host "  ⚠️ 未能获取最新版本" -ForegroundColor Yellow
            continue
        }
        Write-Host "  最新版本: $latest"
        # 版本比较(使用 [version] 类型进行比较)
        $currentVer = [version]$current
        $latestVer = [version]$latest
        if ($latestVer -gt $currentVer) {
            Write-Host "  ✅ 发现更新!" -ForegroundColor Green
            # 弹出通知
            $notify = New-Object System.Windows.Forms.NotifyIcon
            $notify.Icon = [System.Drawing.SystemIcons]::Information
            $notify.Visible = $true
            $notify.ShowBalloonTip(10000, "软件更新提醒", "$($app.Name) 有新版可用!`n当前: $current → 最新: $latest`n下载: $($app.DownloadUrl)", [System.Windows.Forms.ToolTipIcon]::Info)
            # 可选:打开下载页面
            Start-Process $app.DownloadUrl
        } else {
            Write-Host "  ✔️ 已是最新版" -ForegroundColor Gray
        }
    } catch {
        Write-Host "  ❌ 检查失败: $_" -ForegroundColor Red
    }
    Write-Host "------------------------"
}
# 保持窗口(双击运行时)
Read-Host "按 Enter 退出"

使用方式

  1. 将以上代码保存为 check-updates.ps1
  2. 右键 → 使用 PowerShell 运行
  3. 如需定时运行:
    • 打开“任务计划程序”
    • 创建任务 → 触发器设为“每天”或“登录时”
    • 操作 → 启动程序 → powershell.exe
    • 参数: -ExecutionPolicy Bypass -File "C:\路径\check-updates.ps1"

macOS/Linux Shell 脚本(适合命令行环境)

这个脚本会使用 brewapt 等包管理器,以及检查常见应用(Chrome、VS Code、Docker)的最新版本。

#!/bin/bash
# 文件名: check-updates.sh
# 用法: bash check-updates.sh 或添加到 cron
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
echo -e "${CYAN}=== 软件更新检查 ===${NC}"
echo "时间: $(date)"
echo "------------------------"
# 检查系统包管理器
if command -v brew &> /dev/null; then
    echo -e "${GREEN}[Homebrew]${NC} 检查..."
    outdated=$(brew outdated 2>/dev/null | head -20)  # 最多显示20个
    if [ -n "$outdated" ]; then
        echo -e "  ${YELLOW}有更新的包:${NC}"
        echo "$outdated" | while IFS= read -r line; do
            echo "    • $line"
        done
        echo "  运行 'brew upgrade' 更新所有"
    else
        echo "  ✔️ 所有 brew 包已是最新"
    fi
fi
if command -v apt &> /dev/null; then
    echo -e "${GREEN}[APT]${NC} 检查..."
    sudo apt update -qq 2>/dev/null
    upgradable=$(apt list --upgradable 2>/dev/null | grep -v "Listing..." | head -20)
    if [ -n "$upgradable" ]; then
        echo -e "  ${YELLOW}可更新的 APT 包:${NC}"
        echo "$upgradable"
        echo "  运行 'sudo apt upgrade' 更新"
    else
        echo "  ✔️ 所有 APT 包已是最新"
    fi
fi
# 检查独立安装的应用
echo -e "${GREEN}[Google Chrome]${NC}"
if command -v google-chrome &> /dev/null || command -v google-chrome-stable &> /dev/null; then
    # 获取当前版本
    chrome_current=$(google-chrome-stable --version 2>/dev/null | grep -oP '\d+\.\d+\.\d+' | head -1)
    if [ -z "$chrome_current" ]; then
        chrome_current=$(google-chrome --version 2>/dev/null | grep -oP '\d+\.\d+\.\d+' | head -1)
    fi
    echo "  当前版本: $chrome_current"
    # 获取最新版本(从 Google API)
    chrome_latest=$(curl -s "https://omahaproxy.appspot.com/win?channel=stable&platform=win64&json=1" | python3 -c "import sys,json; print(json.load(sys.stdin)['versions'][0]['version'])" 2>/dev/null)
    if [ -n "$chrome_latest" ]; then
        echo "  最新版本: $chrome_latest"
        if [ "$chrome_current" != "$chrome_latest" ]; then
            echo -e "  ${YELLOW}➡️ 有更新可用${NC}"
            echo "  下载: https://www.google.com/chrome/"
        else
            echo "  ✔️ 已是最新版"
        fi
    else
        echo "  ⚠️ 无法获取最新版本"
    fi
else
    echo -e "  ${RED}❌ 未安装 Chrome${NC}"
fi
echo -e "${GREEN}[Visual Studio Code]${NC}"
if command -v code &> /dev/null; then
    vsc_current=$(code --version 2>/dev/null | head -1)
    echo "  当前版本: $vsc_current"
    # 从 GitHub API 获取最新版本
    vsc_latest=$(curl -s "https://api.github.com/repos/microsoft/vscode/releases/latest" | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'].lstrip('v'))" 2>/dev/null)
    if [ -n "$vsc_latest" ]; then
        echo "  最新版本: $vsc_latest"
        if [ "$vsc_current" != "$vsc_latest" ] && [ "$(printf '%s\n' "$vsc_latest" "$vsc_current" | sort -V | tail -1)" = "$vsc_latest" ]; then
            echo -e "  ${YELLOW}➡️ 有更新可用${NC}"
            echo "  运行 'brew upgrade --cask visual-studio-code' 或手动下载"
        else
            echo "  ✔️ 已是最新版"
        fi
    else
        echo "  ⚠️ 无法获取最新版本"
    fi
else
    echo -e "  ${RED}❌ 未安装 VS Code${NC}"
fi
echo -e "${GREEN}[Docker]${NC}"
if command -v docker &> /dev/null; then
    docker_current=$(docker --version 2>/dev/null | grep -oP '\d+\.\d+\.\d+' | head -1)
    echo "  当前版本: $docker_current"
    # Docker 版本检查(简化)
    docker_latest=$(curl -s "https://hub.docker.com/v2/repositories/library/docker/tags?page_size=1&ordering=last_updated" | python3 -c "import sys,json; print(json.load(sys.stdin)['results'][0]['name'])" 2>/dev/null)
    # 注意:这里获取的是最新标签,可能不准确,仅供参考
    if [ -n "$docker_latest" ]; then
        echo "  最新标签: $docker_latest"
    fi
else
    echo -e "  ${RED}❌ 未安装 Docker${NC}"
fi
echo "------------------------"
echo -e "${GREEN}检查完成!${NC}"
echo "提示: 可添加到 crontab 实现自动检查:"
echo "  0 9 * * * bash $(pwd)/$0"

使用方式

  1. 保存为 check-updates.sh
  2. 赋予执行权限:chmod +x check-updates.sh
  3. 运行:bash check-updates.sh
  4. 定时执行:crontab -e 添加一行:
    0 9 * * * /bin/bash /home/你的用户名/check-updates.sh

脚本核心原理

  1. 获取当前版本

    • Windows:读取注册表 Uninstall 键下的 DisplayVersion
    • macOS/Linux:--version 命令输出、包管理器信息
  2. 获取最新版本

    • 调用官方 API(JSON/XML)
    • 解析 HTML 页面(用正则匹配版本号)
    • 使用包管理器检查(brew outdated / apt list --upgradable
  3. 版本比较

    • 使用 [version] 类型(Windows)或 sort -V(Linux)进行语义化版本比较
  4. 通知方式

    • Windows:System.Windows.Forms.NotifyIcon 气泡提示
    • macOS/Linux:终端输出 + 可配合 notify-send 命令

进阶用法(推荐工具)

如果不想自己写脚本,可以考虑现成的工具:

  • Windows:

    • Winget(微软官方包管理器): winget upgrade --all
    • Chocolatey: choco outdated
    • Scoop: scoop update *
  • macOS: brew update && brew outdated

  • Linux: 各发行版包管理器自带更新通知

我的脚本可以作为一个定制化的补充 —— 如果你想监控某些特定软件(比如公司内网工具、没有上架包管理器的软件),这个模板会很实用。

需要我帮你适配某个具体软件的更新检查吗?告诉我应用名称,我可以添加对应的检测代码。

抱歉,评论功能暂时关闭!