自动化工具 Windows 包管理器:Chocolatey

狄仁杰666 · August 27, 2025 · 136 hits

近期在琢磨如何管理多台 windows 设备,以便更快速的克隆出一致的 windows 设备,我能想到的是使用 Ansible,笔者也用自己的 windows 电脑实际调研操作了一番,最后被卡在 company policy,无奈放弃。

我的出发点是能抽象软件安装过程与系统配置过程,能实现软件安装过程与系统配置的自动化即可。因此,最后我折中选择 Chocolatey。

感兴趣的朋友一起来看看吧!

学习路径

一、什么是 Chocolatey?

二、Chocolatey 的特点;

三、如何安装 Chocolatey?

四、具体案例演示;

五、总结;


一、什么是 Chocolatey?

Chocolatey 是一个用于 Windows 的包管理器,它使得软件的安装、更新和管理变得简单而高效。类似于 Linux 上的 APT 或 Yum,Chocolatey 和 macOS 上的 Homebrew(通常简称为 Brew)在功能和目的上非常相似,Chocolatey 允许用户通过命令行轻松地在 windows 电脑上安装和管理软件包,从而简化了软件管理的过程。


二、Chocolatey 的特点

1. 简化软件安装
使用 Chocolatey,用户可以通过简单的命令行指令快速安装软件。例如,要安装 Google Chrome,只需在命令提示符或 PowerShell 中输入:

choco install googlechrome

这条命令会自动下载并安装 Google Chrome,而无需用户手动访问网站或下载文件。

2. 自动更新
Chocolatey 还支持软件的自动更新。用户可以使用以下命令更新已安装的软件包:

choco upgrade all

这将检查所有已安装的软件包,并自动更新到最新版本,确保用户始终使用最新的软件。

3. 丰富的软件库
Chocolatey 拥有一个庞大的软件库,用户可以通过 Chocolatey 安装数千种应用程序和工具。无论是开发工具、浏览器、IDE 还是其他常用软件,Chocolatey 都能提供便捷的安装方式。

4. 易于管理
Chocolatey 提供了一系列命令来管理已安装的软件包。用户可以轻松地列出已安装的软件、卸载软件、查看软件信息等。例如,列出所有已安装的软件包:

choco list --local-only

5. 支持脚本和自动化
Chocolatey 可以与 PowerShell 脚本结合使用,支持自动化软件安装和配置。这对于开发人员和系统管理员来说非常有用,可以通过脚本快速设置开发环境或部署软件。


三、如何安装 Chocolatey?

安装 Chocolatey 非常简单。以下是安装步骤:

  • 打开 PowerShell(以管理员身份运行)。 运行以下命令:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

  • 验证安装; 安装完成后,可以通过运行以下命令来验证 Chocolatey 是否安装成功:
choco --version

且生成了 C:\ProgramData\chocolatey 目录,目录结构如下:

常见问题:

  • 如果没有以管理员身份运行的话,则会报如下错误;

  • 如果用非管理员安装,即使失败,可能也会创建 C:\ProgramData\chocolatey 文件夹,导致再次使用管理员身份安装 chocolatey 时会提示 chocolatey 已安装而停止;

  • 此时可以执行卸载 chocolatey 命令再重新安装即可;
Remove-Item -Recurse -Force "C:\ProgramData\chocolatey"

四、具体案例演示;

  1. Demo 脚本; 以下脚本实现了:
  2. 检查当前是否是管理员;
  3. 获取当前电脑的电脑名与 ip 地址;
  4. 检查当前是否安装了 chocolatey,如果未安装则安装;
  5. 根据安装列表逐个检查、安装,列表有:python3、git;
  6. 安装完 python3 需要设置一下环境变量;
  7. 使用 chocolatey 安装自定义软件 test.exe;
# Check if running as administrator
#Requires -RunAsAdministrator
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Error "Please run this script as Administrator!"
    exit 1
}

# Get current computer name and IP addresses
$computerName = $env:COMPUTERNAME
$ipAddresses = Get-NetIPAddress | Where-Object {
    $_.AddressFamily -eq 'IPv4' -and 
    $_.InterfaceAlias -notlike 'Loopback*' -and
    $_.Status -eq 'Up'
} | Select-Object -ExpandProperty IPAddress

Write-Host "`nComputer Name: $computerName"
Write-Host "IP Address(es):"
$ipAddresses | ForEach-Object { Write-Host "  - $_" }

# Check and install Chocolatey
Write-Host "`nChecking Chocolatey installation status..."
if (-not (Get-Command -Name choco -ErrorAction SilentlyContinue)) {
    Write-Host "Chocolatey not installed, installing now..."
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
    Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

    # Refresh environment variables to make choco command available immediately
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")

    if (Get-Command -Name choco -ErrorAction SilentlyContinue) {
        Write-Host "Chocolatey installed successfully"
    } else {
        Write-Error "Failed to install Chocolatey"
        exit 1
    }
} else {
    Write-Host "Chocolatey is already installed"
}

# Define list of software to install
$softwareList = @("python3", "git")

# Check and install software
foreach ($software in $softwareList) {
    Write-Host "`nChecking $software installation status..."
    $installed = choco list --localonly --exact $software | Where-Object { $_ -match "^$software \d" }

    if (-not $installed) {
        Write-Host "Installing $software..."
        choco install $software -y --no-progress
        if ($LASTEXITCODE -eq 0) {
            Write-Host "$software installed successfully"
        } else {
            Write-Error "Failed to install $software"
        }
    } else {
        Write-Host "$software is already installed"
    }
}

# Configure Python3 environment variables (dynamically detect path)
Write-Host "`nConfiguring Python3 environment variables..."

# Method 1: Get installation path from Chocolatey install information
$pythonInstallInfo = choco list --localonly --exact python3 --verbose
$installPathMatch = $pythonInstallInfo -match "Install location: (.*)"
if ($installPathMatch) {
    $pythonPath = $matches[1]
}
else {
    # Method 2: Derive from executable path if Method 1 fails
    try {
        $pythonExePath = Get-Command python -ErrorAction Stop | Select-Object -ExpandProperty Source
        $pythonPath = Split-Path $pythonExePath -Parent
    }
    catch {
        # Method 3: Check common installation paths as last resort
        $programFiles = $env:ProgramFiles
        $pythonPath = Get-ChildItem -Path "$programFiles\Python*" -Directory | Select-Object -First 1 -ExpandProperty FullName
    }
}

# Verify path exists
if (-not $pythonPath -or -not (Test-Path $pythonPath)) {
    Write-Error "Could not detect Python installation path, please configure environment variables manually"
}
else {
    $pipPath = Join-Path $pythonPath "Scripts"

    # Add to system environment variables
    $envPath = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
    $pathsToAdd = @()

    if ($envPath -notlike "*$pythonPath*") {
        $pathsToAdd += $pythonPath
    }
    if ($envPath -notlike "*$pipPath*") {
        $pathsToAdd += $pipPath
    }

    if ($pathsToAdd.Count -gt 0) {
        $newEnvPath = $envPath + ";" + ($pathsToAdd -join ";")
        [System.Environment]::SetEnvironmentVariable("Path", $newEnvPath, "Machine")
        Write-Host "Added the following paths to system environment variables:"
        $pathsToAdd | ForEach-Object { Write-Host "  - $_" }
    } 
    else {
        Write-Host "Python environment variables are already configured"
    }

    # Refresh environment variables for current session
    $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}

# Install custom software test.exe
Write-Host "`nInstalling custom software test.exe..."
if (Test-Path ".\test.exe") {
    choco install test -s ".\test.exe" -y --no-progress
} 
else {
    Write-Host "test.exe not found, attempting to install from network..."
    # If you have a network address, use the following command
    # choco install test -s "https://example.com/test.exe" -y --no-progress
    Write-Warning "test.exe not found, please ensure the file exists in the current directory"
}

Write-Host "`nAll operations completed!`n"

  • 我们可以根据需要,添加要安装的软件到软件安装列表,如添加安装 chrome 浏览器,则:
$softwareList = @("python3", "git")

改为:

$softwareList = @("python3", "git", "googlechrome")

即可;

  • 执行脚本安装;

  • 再次执行脚本确认是否安装成功;

4. 卸载软件;

在 Chocolatey 中卸载软件可以使用 choco uninstall 命令,基本语法如下:

卸载指定软件(以卸载 Chrome 为例)

choco uninstall googlechrome -y

卸载多个软件

choco uninstall python3 git -y

常用参数说明:

  • -y:自动确认卸载(无需手动输入 Y 确认)
  • --all-versions:卸载该软件的所有版本(如果安装了多个版本)
  • -n 或 --no-progress:不显示进度条
  • --purge:彻底卸载,包括配置文件(部分软件支持)


五、总结;

Chocolatey 是一个强大的工具,极大地简化了 Windows 上软件的安装和管理。无论是个人用户还是企业环境,Chocolatey 都能提供高效、便捷的软件管理体验。通过 Chocolatey,用户可以节省时间,专注于更重要的任务,而不是花费大量时间在软件安装和更新上。

可以预料,我只需要把要安装的软件,以及把要修改的系统配置在 install_packages.ps1 定义好,就可以很快克隆出相同的 windows 设备了,而 install_packages.ps1 将成为新的团队资产!

免费的点赞、关注来一个?感恩~

No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up