近期在琢磨如何管理多台 windows 设备,以便更快速的克隆出一致的 windows 设备,我能想到的是使用 Ansible,笔者也用自己的 windows 电脑实际调研操作了一番,最后被卡在 company policy,无奈放弃。
我的出发点是能抽象软件安装过程与系统配置过程,能实现软件安装过程与系统配置的自动化即可。因此,最后我折中选择 Chocolatey。
感兴趣的朋友一起来看看吧!
Chocolatey 是一个用于 Windows 的包管理器,它使得软件的安装、更新和管理变得简单而高效。类似于 Linux 上的 APT 或 Yum,Chocolatey 和 macOS 上的 Homebrew(通常简称为 Brew)在功能和目的上非常相似,Chocolatey 允许用户通过命令行轻松地在 windows 电脑上安装和管理软件包,从而简化了软件管理的过程。
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 非常简单。以下是安装步骤:
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'))
choco --version
且生成了 C:\ProgramData\chocolatey 目录,目录结构如下:
常见问题:
Remove-Item -Recurse -Force "C:\ProgramData\chocolatey"
# 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"
$softwareList = @("python3", "git")
改为:
$softwareList = @("python3", "git", "googlechrome")
即可;
在 Chocolatey 中卸载软件可以使用 choco uninstall 命令,基本语法如下:
choco uninstall googlechrome -y
choco uninstall python3 git -y
常用参数说明:
Chocolatey 是一个强大的工具,极大地简化了 Windows 上软件的安装和管理。无论是个人用户还是企业环境,Chocolatey 都能提供高效、便捷的软件管理体验。通过 Chocolatey,用户可以节省时间,专注于更重要的任务,而不是花费大量时间在软件安装和更新上。
可以预料,我只需要把要安装的软件,以及把要修改的系统配置在 install_packages.ps1 定义好,就可以很快克隆出相同的 windows 设备了,而 install_packages.ps1 将成为新的团队资产!