Step 1: Subscribe to the Chocolatey Newsletter (Optional)
Be the first to know about upcoming features, security releases, and news about Chocolatey.
Step 2: Choose Your Installation Method
Know the Requirements:
- Windows 7+ / Windows Server 2003+
- PowerShell v2+ (minimum is v3 for install from this website due to TLS 1.2 requirement)
- .NET Framework 4+ (the installation will attempt to install .NET 4.0 if you do not have it installed)(minimum is 4.5 for install from this website due to TLS 1.2 requirement)
1. Choose How to Install Chocolatey:
Install Chocolatey for Individual Use:
- First, ensure that you are using an administrative shell — you can also install as a non-admin, check out Non-Administrative Installation.
-
Install with powershell.exe
With PowerShell, you must ensure Get-ExecutionPolicy is not Restricted. We suggest using
Bypass
to bypass the policy to get things installed orAllSigned
for quite a bit more security.- Run
Get-ExecutionPolicy
. If it returnsRestricted
, then runSet-ExecutionPolicy AllSigned
orSet-ExecutionPolicy Bypass -Scope Process
.
Now run the following command:
>
- Run
- Paste the copied text into your shell and press Enter.
- Wait a few seconds for the command to complete.
- If you don’t see any errors, you are ready to use Chocolatey! Type
choco
orchoco -?
now, or see Getting Started for usage instructions.
This applies to both open source and commercial editions of Chocolatey.
2. Enter Your Internal Repository Url
(this should look similar to https://community.chocolatey.org/api/v2/)
3. Setup Your Environment
- Ensure you are set for organizational deployment
-
Download the Chocolatey package
- Put the Chocolatey package on your internal repository
4. Get Your Scripts
1. Save this installation script
Save the following as ChocolateyInstall.ps1:
# Download and install Chocolatey nupkg from an OData (HTTP/HTTPS) url such as Artifactory, Nexus, ProGet (all of these are recommended for organizational use), or Chocolatey.Server (great for smaller organizations and POCs)
# This is where you see the top level API - with xml to Packages - should look nearly the same as https://community.chocolatey.org/api/v2/
# If you are using Nexus, always add the trailing slash or it won't work
# === EDIT HERE ===
$packageRepo = 'INTERNAL REPO URL'
# If the above $packageRepo repository requires authentication, add the username and password here. Otherwise these leave these as empty strings.
$repoUsername = '' # this must be empty is NOT using authentication
$repoPassword = '' # this must be empty if NOT using authentication
# Determine unzipping method
# 7zip is the most compatible, but you need an internally hosted 7za.exe.
# Make sure the version matches for the arguments as well.
# Built-in does not work with Server Core, but if you have PowerShell 5
# it uses Expand-Archive instead of COM
$unzipMethod = 'builtin'
#$unzipMethod = '7zip'
#$7zipUrl = 'https://chocolatey.org/7za.exe' (download this file, host internally, and update this to internal)
# === ENVIRONMENT VARIABLES YOU CAN SET ===
# Prior to running this script, in a PowerShell session, you can set the
# following environment variables and it will affect the output
# - $env:ChocolateyEnvironmentDebug = 'true' # see output
# - $env:chocolateyIgnoreProxy = 'true' # ignore proxy
# - $env:chocolateyProxyLocation = '' # explicit proxy
# - $env:chocolateyProxyUser = '' # explicit proxy user name (optional)
# - $env:chocolateyProxyPassword = '' # explicit proxy password (optional)
# === NO NEED TO EDIT ANYTHING BELOW THIS LINE ===
# Ensure we can run everything
Set-ExecutionPolicy Bypass -Scope Process -Force;
# If the repository requires authentication, create the Credential object
if ((-not [string]::IsNullOrEmpty($repoUsername)) -and (-not [string]::IsNullOrEmpty($repoPassword))) {
$securePassword = ConvertTo-SecureString $repoPassword -AsPlainText -Force
$repoCreds = New-Object System.Management.Automation.PSCredential ($repoUsername, $securePassword)
}
$searchUrl = ($packageRepo.Trim('/'), 'Packages()?$filter=(Id%20eq%20%27chocolatey%27)%20and%20IsLatestVersion') -join '/'
# Reroute TEMP to a local location
New-Item $env:ALLUSERSPROFILEchoco-cache -ItemType Directory -Force
$env:TEMP = "$env:ALLUSERSPROFILEchoco-cache"
$localChocolateyPackageFilePath = Join-Path $env:TEMP 'chocolatey.nupkg'
$ChocoInstallPath = "$($env:SystemDrive)ProgramDataChocolateybin"
$env:ChocolateyInstall = "$($env:SystemDrive)ProgramDataChocolatey"
$env:Path += ";$ChocoInstallPath"
$DebugPreference = 'Continue';
# PowerShell v2/3 caches the output stream. Then it throws errors due
# to the FileStream not being what is expected. Fixes "The OS handle's
# position is not what FileStream expected. Do not use a handle
# simultaneously in one FileStream and in Win32 code or another
# FileStream."
function Fix-PowerShellOutputRedirectionBug {
$poshMajorVerion = $PSVersionTable.PSVersion.Major
if ($poshMajorVerion -lt 4) {
try{
# http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ plus comments
$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField"
$objectRef = $host.GetType().GetField("externalHostRef", $bindingFlags).GetValue($host)
$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetProperty"
$consoleHost = $objectRef.GetType().GetProperty("Value", $bindingFlags).GetValue($objectRef, @())
[void] $consoleHost.GetType().GetProperty("IsStandardOutputRedirected", $bindingFlags).GetValue($consoleHost, @())
$bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField"
$field = $consoleHost.GetType().GetField("standardOutputWriter", $bindingFlags)
$field.SetValue($consoleHost, [Console]::Out)
[void] $consoleHost.GetType().GetProperty("IsStandardErrorRedirected", $bindingFlags).GetValue($consoleHost, @())
$field2 = $consoleHost.GetType().GetField("standardErrorWriter", $bindingFlags)
$field2.SetValue($consoleHost, [Console]::Error)
} catch {
Write-Output 'Unable to apply redirection fix.'
}
}
}
Fix-PowerShellOutputRedirectionBug
# Attempt to set highest encryption available for SecurityProtocol.
# PowerShell will not set this by default (until maybe .NET 4.6.x). This
# will typically produce a message for PowerShell v2 (just an info
# message though)
try {
# Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192)
# Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't
# exist in .NET 4.0, even though they are addressable if .NET 4.5+ is
# installed (.NET 4.5 is an in-place upgrade).
[System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192
} catch {
Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3+.'
}
function Get-Downloader {
param (
[string]$url
)
$downloader = new-object System.Net.WebClient
$defaultCreds = [System.Net.CredentialCache]::DefaultCredentials
if (Test-Path -Path variable:repoCreds) {
Write-Debug "Using provided repository authentication credentials."
$downloader.Credentials = $repoCreds
} elseif ($defaultCreds -ne $null) {
Write-Debug "Using default repository authentication credentials."
$downloader.Credentials = $defaultCreds
}
$ignoreProxy = $env:chocolateyIgnoreProxy
if ($ignoreProxy -ne $null -and $ignoreProxy -eq 'true') {
Write-Debug 'Explicitly bypassing proxy due to user environment variable.'
$downloader.Proxy = [System.Net.GlobalProxySelection]::GetEmptyWebProxy()
} else {
# check if a proxy is required
$explicitProxy = $env:chocolateyProxyLocation
$explicitProxyUser = $env:chocolateyProxyUser
$explicitProxyPassword = $env:chocolateyProxyPassword
if ($explicitProxy -ne $null -and $explicitProxy -ne '') {
# explicit proxy
$proxy = New-Object System.Net.WebProxy($explicitProxy, $true)
if ($explicitProxyPassword -ne $null -and $explicitProxyPassword -ne '') {
$passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force
$proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd)
}
Write-Debug "Using explicit proxy server '$explicitProxy'."
$downloader.Proxy = $proxy
} elseif (!$downloader.Proxy.IsBypassed($url)) {
# system proxy (pass through)
$creds = $defaultCreds
if ($creds -eq $null) {
Write-Debug 'Default credentials were null. Attempting backup method'
$cred = get-credential
$creds = $cred.GetNetworkCredential();
}
$proxyaddress = $downloader.Proxy.GetProxy($url).Authority
Write-Debug "Using system proxy server '$proxyaddress'."
$proxy = New-Object System.Net.WebProxy($proxyaddress)
$proxy.Credentials = $creds
$downloader.Proxy = $proxy
}
}
return $downloader
}
function Download-File {
param (
[string]$url,
[string]$file
)
$downloader = Get-Downloader $url
$downloader.DownloadFile($url, $file)
}
function Download-Package {
param (
[string]$packageODataSearchUrl,
[string]$file
)
$downloader = Get-Downloader $packageODataSearchUrl
Write-Output "Querying latest package from $packageODataSearchUrl"
[xml]$pkg = $downloader.DownloadString($packageODataSearchUrl)
$packageDownloadUrl = $pkg.feed.entry.content.src
Write-Output "Downloading $packageDownloadUrl to $file"
$downloader.DownloadFile($packageDownloadUrl, $file)
}
function Install-ChocolateyFromPackage {
param (
[string]$chocolateyPackageFilePath = ''
)
if ($chocolateyPackageFilePath -eq $null -or $chocolateyPackageFilePath -eq '') {
throw "You must specify a local package to run the local install."
}
if (!(Test-Path($chocolateyPackageFilePath))) {
throw "No file exists at $chocolateyPackageFilePath"
}
$chocTempDir = Join-Path $env:TEMP "chocolatey"
$tempDir = Join-Path $chocTempDir "chocInstall"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}
$file = Join-Path $tempDir "chocolatey.zip"
Copy-Item $chocolateyPackageFilePath $file -Force
# unzip the package
Write-Output "Extracting $file to $tempDir..."
if ($unzipMethod -eq '7zip') {
$7zaExe = Join-Path $tempDir '7za.exe'
if (-Not (Test-Path ($7zaExe))) {
Write-Output 'Downloading 7-Zip commandline tool prior to extraction.'
# download 7zip
Download-File $7zipUrl "$7zaExe"
}
$params = "x -o`"$tempDir`" -bd -y `"$file`""
# use more robust Process as compared to Start-Process -Wait (which doesn't
# wait for the process to finish in PowerShell v3)
$process = New-Object System.Diagnostics.Process
$process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($7zaExe, $params)
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$process.Start() | Out-Null
$process.BeginOutputReadLine()
$process.WaitForExit()
$exitCode = $process.ExitCode
$process.Dispose()
$errorMessage = "Unable to unzip package using 7zip. Perhaps try setting `$env:chocolateyUseWindowsCompression = 'true' and call install again. Error:"
switch ($exitCode) {
0 { break }
1 { throw "$errorMessage Some files could not be extracted" }
2 { throw "$errorMessage 7-Zip encountered a fatal error while extracting the files" }
7 { throw "$errorMessage 7-Zip command line error" }
8 { throw "$errorMessage 7-Zip out of memory" }
255 { throw "$errorMessage Extraction cancelled by the user" }
default { throw "$errorMessage 7-Zip signalled an unknown error (code $exitCode)" }
}
} else {
if ($PSVersionTable.PSVersion.Major -lt 5) {
try {
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($file)
$destinationFolder = $shellApplication.NameSpace($tempDir)
$destinationFolder.CopyHere($zipPackage.Items(),0x10)
} catch {
throw "Unable to unzip package using built-in compression. Set `$env:chocolateyUseWindowsCompression = 'false' and call install again to use 7zip to unzip. Error: `n $_"
}
} else {
Expand-Archive -Path "$file" -DestinationPath "$tempDir" -Force
}
}
# Call Chocolatey install
Write-Output 'Installing chocolatey on this machine'
$toolsFolder = Join-Path $tempDir "tools"
$chocInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1"
& $chocInstallPS1
Write-Output 'Ensuring chocolatey commands are on the path'
$chocInstallVariableName = 'ChocolateyInstall'
$chocoPath = [Environment]::GetEnvironmentVariable($chocInstallVariableName)
if ($chocoPath -eq $null -or $chocoPath -eq '') {
$chocoPath = 'C:ProgramDataChocolatey'
}
$chocoExePath = Join-Path $chocoPath 'bin'
if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) {
$env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine);
}
Write-Output 'Ensuring chocolatey.nupkg is in the lib folder'
$chocoPkgDir = Join-Path $chocoPath 'libchocolatey'
$nupkg = Join-Path $chocoPkgDir 'chocolatey.nupkg'
if (!(Test-Path $nupkg)) {
Write-Output 'Copying chocolatey.nupkg is in the lib folder'
if (![System.IO.Directory]::Exists($chocoPkgDir)) { [System.IO.Directory]::CreateDirectory($chocoPkgDir); }
Copy-Item "$file" "$nupkg" -Force -ErrorAction SilentlyContinue
}
}
# Idempotence - do not install Chocolatey if it is already installed
if (!(Test-Path $ChocoInstallPath)) {
# download the package to the local path
if (!(Test-Path $localChocolateyPackageFilePath)) {
Download-Package $searchUrl $localChocolateyPackageFilePath
}
# Install Chocolatey
Install-ChocolateyFromPackage $localChocolateyPackageFilePath
}
2. Make script accessible by internal url
Put the script somewhere internally that can be accessed by a url (like a raw/binary repository in Nexus, Artifactory, or ProGet). Do NOT put the script on a NuGet type repository (where your packages will be), create a new Raw/Binary repository.
3. Install/Deploy Chocolatey internally
Now you can do similar to the individual side, but your command will be something like:
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('INTERNAL REPO URL/ChocolateyInstall.ps1'))
3. Add the following to your playbook
# Note: `chocolateyDownloadUrl is completely different than normal
# source locations. This is directly to the bare download url for the
# chocolatey.nupkg, similar to what you see when you browse to
# https://community.chocolatey.org/api/v2/package/chocolatey
node['chocolatey']['install_vars']['chocolateyDownloadUrl'] = 'INTERNAL REPO URL/check_this/chocolatey.VERSION.nupkg'
node['chocolatey']['upgrade'] = true
include_recipe 'chocolatey::default'
The install of Chocolatey is separate from the Chef built-in resources. You will need the Chocolatey Cookbook.
3. Add the following to your DSC script:
cChocoInstaller InstallChocolatey
{
InstallDir = "C:ProgramDatachocolatey"
ChocoInstallScriptUrl = "INTERNAL REPO URL/ChocolateyInstall.ps1"
}
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
## Note: `chocolatey_download_url is completely different than normal
## source locations. This is directly to the bare download url for the
## chocolatey.nupkg, similar to what you see when you browse to
## https://community.chocolatey.org/api/v2/package/chocolatey
class {'chocolatey':
chocolatey_download_url => 'INTERNAL REPO URL/check_this/chocolatey.VERSION.nupkg',
use_7zip => false,
}
Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.
5. If applicable — Chocolatey configuration/installation
See infrastructure management matrix for Chocolatey configuration elements and examples.
Chocolatey Licensed Install:
Are you also installing a commercial edition of Chocolatey?
Please see Install the Licensed Edition.
Advanced Chocolatey Install:
Are you installing behind a proxy, need a completely offline install, or wanting to install a licenced edition of Chocolatey? Need even more options? Visit our Documentation or take our new Installation Course to help you get up and running with Chocolatey!
Как сказал один мудрец (и по совместительству просто мой друг):
“нет плохих или хороших операционных систем, есть подходящие и
не подходящие для решения конкретных пользовательских задач”.
Глубокая мысль, я с этим полностью согласен.
Хотя для решения конкретно моих рабочих задач намного лучше подходят
другие ОС, у Windows тоже есть своя ниша.
Я уже давно привык пользоваться в повседневной деятельности
Unix-подобными операционными системами, такими как Fedora Linux и macOS.
Но недавно я решил совершить очередной набег в мир Windows
— попробовать новые классные фичи WSL2
да в игры поиграть.
Только в этот раз я решил сразу сделать всё по-правильному, и
устанавливать весь софт так, чтобы им потом было удобно управлять и обновлять.
В поисках решения этой задачи я открыл для себя
замечательный инструмент Chocolatey,
который теперь считаю жизненно необходимым для комфортного пользования
Windows.
Chocolatey — это пакетный менеджер для Windows,
примерно как apt
в мире Debian/Ubuntu или
dnf
в мире Fedora/CentOS.
Пакетный менеджер занимается установкой, удалением и обновлением программ.
Если вам, как и мне, надоело ставить галочки под текстом лицензии
(хоть раз вообще читали?)
и безразлично нажимать кнопку “далее”, то Chocolatey вам поможет.
Он имеет интерфейс командной строки — то, что надо для такого гика, как я!
У Chocolatey большая библиотека пакетов
— больше 7500 штук, всё популярное там точно есть.
Хоть я привёл в пример apt
и dnf
, на самом деле,
Chocolatey имеет намного больше общего с
Homebrew — пакетным менеджером для macOS.
В Linux пакетные менеджеры уже давно стали насущной необходимостью
— там этим никого не удивить, а Chocolatey и Homebrew работают в окружениях,
где изначально пакетные менеджеры не предусмотрены.
При этом оба они отлично справляются со своими задачами.
Chocolatey написан на C# и PowerShell, имеет
открытый исходный код.
Для работы требует Windows 7 или новее.
Установка
Чтобы установить Chocolatey, нужно запустить командную строку
с правами администратора. Сделать это в Windows 10 можно так:
- Нажимаем на клавиатуре кнопку Win или просто открываем меню «Пуск»;
- Набираем
cmd
; - На найденной программе нажимаем правой кнопкой мыши
и выбираем пункт “Run as administrator” или, в русской локализации,
“Запуск от имени администратора”.
В открывшееся окно терминала нужно вставить следующую команду:
@"%SystemRoot%System32WindowsPowerShellv1.0powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command " [System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin"
На всякий случай, если эта команда устареет и перестанет работать,
или вы предпочитаете вставлять в администраторский терминал команды
только из официальных источников (и правильно делаете), то документация
по установке находится
вот здесь.
После того, как команда отработает (у меня установка заняла примерно минуту),
нужно перезапустить терминал. Вместо cmd
можно запустить PowerShell (тоже от имени администратора) — он немного
удобнее. Можно проверить установку:
Если вы видите справку по команде, то установка прошла успешно.
Установка программ
Давайте установим через choco
первые программы.
Все эти программы найдены в реестре пакетов
и проверены мной — работают.
При установке вы можете заметить, что все программы скачиваются с
официальных сайтов разработчиков.
Если вы переживаете по поводу вирусов, то рекомендую почитать,
какие меры предпринимают мейнтейнеры Chocolatey,
чтобы обеспечить безопасность пакетов (там всё серьезно).
Во всех командах я добавил флаг -y
, чтобы установщик не задавал
вообще никаких вопросов. Эта команда автоматически соглашается с
лицензиями и разрешает запуск скриптов установки. Ради интереса
можете попробовать убрать этот флаг из команд, и посмотреть, что будет.
Допустим, что вам нужен браузер (удалите из команды ненужные названия):
choco install -y googlechrome firefox
Или текстовый редактор/IDE (удалите из команды ненужные названия):
choco install -y notepadplusplus.install vscode
Я являюсь заядлым пользователем PyCharm, который лучше всего устанавливать
через JetBrains Toolbox
(как и любые другие IDE от JetBrains):
choco install -y jetbrainstoolbox
Инструменты для разработки:
choco install -y git python3 microsoft-windows-terminal postman
Мессенджеры и видео-конференции:
choco install -y telegram.install slack zoom
Игры:
choco install -y steam epicgameslauncher
Всякое прочее-разное полезное:
choco install -y 7zip vlc paint.net teamviewer qbittorrent thunderbird putty.install
И для установки даже не пришлось кликать мышью по кнопкам!
Тут можете почитать
про удаление программ при помощи choco
.
Обновление
Вот так можно обновить все установленные через choco
программы
до актуальных версий:
По-моему, это очень круто и удобно!
Заключение
choco
— теперь для меня это просто маст-хэв на Windows.
Самая первая программа, которую я буду устанавливать.
Благодаря Chocolatey, для меня Windows стала немного дружелюбнее.
Всем рекомендую попробовать!
Если понравилась статья, то
подпишитесь на уведомления
о новых постах в блоге, чтобы ничего не пропустить!
Дополнительное чтение
- официальный сайт Chocolatey;
- реестр пакетов;
- исходный код;
- видео про Chocolatey для тех, кто больше любит воспринимать информацию визуально.
Обложка: Jean Beaufort, Chocolate
- Requirements
- Installing Chocolatey
- Install with cmd.exe
- Install with PowerShell.exe
- Additional considerations
- More Install Options
- Install from PowerShell v3+
- Completely offline install
- Install with Puppet
- Install using PowerShell from cmd.exe
- Install using NuGet Package Manager
- Install using NuGet.exe from PowerShell
- Install downloaded NuGet package from PowerShell
- Install licensed edition
- Installing behind a proxy
- Installing behind an explicit proxy
- Installing to a different location
- Installing a particular version of Chocolatey
- Use Windows built-in compression instead of downloading 7zip
- Installing with restricted TLS
- Option 1 — Host Internally
- Option 2 — Updated PowerShell and .NET
- Option 3 — Manual
- Non-Administrative install
- Upgrading Chocolatey
- Uninstalling Chocolatey
- FAQs
- I’m having trouble installing Chocolatey
- I’m getting a 403 attempting to install
- Why isn’t there an MSI?
Requirements
- Windows 7+ / Windows Server 2003+
- PowerShell v2+ (Not PowerShell Core yet though)(minimum is v3 for install from this website due to TLS 1.2 requirement)
- .NET Framework 4+ (the installation will attempt to install .NET 4.0 if you do not have it installed)(minimum is 4.5 for install from this website due to TLS 1.2 requirement)
That’s it! All you need is choco.exe (that you get from the installation scripts) and you are good to go! No Visual Studio required.
Installing Chocolatey
Chocolatey installs in seconds. You are just a few steps from running choco right now!
- First, ensure that you are using an administrative shell — you can also install as a non-admin, check out Non-Administrative Installation.
- Copy the text specific to your command shell — cmd.exe or powershell.exe.
- Paste the copied text into your shell and press Enter.
- Wait a few seconds for the command to complete.
- If you don’t see any errors, you are ready to use Chocolatey! Type
choco
orchoco -?
now, or see [[Getting Started|GettingStarted]] for usage instructions.
NOTES:
- If you are behind a proxy, please see Installing behind a proxy.
- Need completely offline solution? See Completely Offline Install.
- Installing the licensed edition? See [[install licensed edition|Installation-Licensed]].
- More Options / [[Troubleshooting|Troubleshooting]]
Install with cmd.exe
Run the following command:
@"%SystemRoot%System32WindowsPowerShellv1.0powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "[System.Net.ServicePointManager]::SecurityProtocol = 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin"
Install with PowerShell.exe
With PowerShell, there is an additional step. You must ensure Get-ExecutionPolicy is not Restricted. We suggest using Bypass
to bypass the policy to get things installed or AllSigned
for quite a bit more security.
- Run
Get-ExecutionPolicy
. If it returnsRestricted
, then runSet-ExecutionPolicy AllSigned
orSet-ExecutionPolicy Bypass -Scope Process
. - Now run the following command:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Additional considerations
NOTE: Please inspect https://chocolatey.org/install.ps1 prior to running any of these scripts to ensure safety. We already know it’s safe, but you should verify the security and contents of any script from the internet you are not familiar with. All of these scripts download a remote PowerShell script and execute it on your machine.
We take security very seriously. Learn more.
«Why do I need to enable TLS 1.2 in PowerShell? Shouldn’t it be on by default when I load PowerShell?»
Unfortunately it’s not always a default, and more of the time it is not. The low level is that it depends on .NET Framework and Windows.
- Explicitly set — Basically you need .NET Fx 4.5 at a minimum to be able to explicitly set TLS 1.2.
- Load by default — To have it load by default when you run PowerShell, you need at least .NET Fx 4.7 AND the Operating System’s SystemDefault to have TLS 1.2 enabled.
The load by default is really hard to see, so you should check to ensure it is there. Assume it doesn’t and set explicitly.
More Install Options
- Install from PowerShell v3+
- Completely offline/internal install
- Install with Puppet
- Install using PowerShell from cmd.exe
- Install using NuGet Package Manager
- Install using NuGet.exe from PowerShell
- Install downloaded NuGet package from PowerShell
- Install licensed edition
- Installing behind a proxy
- Installing behind an explicit proxy
- Installing to a different location
- Installing a particular version of Chocolatey
- Use Windows built-in compression instead of downloading 7zip
- Installing with restricted TLS
- Non-Administrative install
Install from PowerShell v3+
NOTE: The command for installing with PowerShell at the top of the page works for all versions of PowerShell from v2 on. This is provided as an additional note for folks who want a more terse command that is easier to remember.
With PowerShell, there is an additional step or two. You must ensure Get-ExecutionPolicy is not Restricted. We suggest using Bypass
to bypass the policy to get things installed or AllSigned
for quite a bit more security.
- Run
Get-ExecutionPolicy
. If it returnsRestricted
, then runSet-ExecutionPolicy AllSigned
orSet-ExecutionPolicy Bypass
. - Now run the following command:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
Completely offline install
With completely offline use of Chocolatey, you want to ensure you remove the default community package source (choco source list
followed by choco source remove -n chocolatey
, or however you would do that with a configuration manager like Puppet).
- The first step with offline is to obtain a copy of the Chocolatey Nupkg (nupkg files are just fancy zip files). Go to https://chocolatey.org/packages/chocolatey and find a version you want.
- Click on Download to download that version’s nupkg file.
- You can also download the latest version directly.
- You can put the chocolatey.nupkg on an internal package repository and then address that full path, similar to how you see in the Puppet provider — https://forge.puppet.com/puppetlabs/chocolatey#manage-chocolatey-installation
- Then you would run a script similar to the below to address that local install. If it is on a repository somewhere, you will need to enhance the below script to get that file (the Chocolatey Puppet provider install script shows that).
# Download and install Chocolatey nupkg from an OData (HTTP/HTTPS) url such as Artifactory, Nexus, ProGet (all of these are recommended for organizational use), or Chocolatey.Server (great for smaller organizations and POCs) # This is where you see the top level API - with xml to Packages - should look nearly the same as https://chocolatey.org/api/v2/ # If you are using Nexus, always add the trailing slash or it won't work # === EDIT HERE === $packageRepo = '<INSERT ODATA REPO URL>' # If the above $packageRepo repository requires authentication, add the username and password here. Otherwise these leave these as empty strings. $repoUsername = '' # this must be empty is NOT using authentication $repoPassword = '' # this must be empty if NOT using authentication # Determine unzipping method # 7zip is the most compatible, but you need an internally hosted 7za.exe. # Make sure the version matches for the arguments as well. # Built-in does not work with Server Core, but if you have PowerShell 5 # it uses Expand-Archive instead of COM $unzipMethod = 'builtin' #$unzipMethod = '7zip' #$7zipUrl = 'https://chocolatey.org/7za.exe' (download this file, host internally, and update this to internal) # === ENVIRONMENT VARIABLES YOU CAN SET === # Prior to running this script, in a PowerShell session, you can set the # following environment variables and it will affect the output # - $env:ChocolateyEnvironmentDebug = 'true' # see output # - $env:chocolateyIgnoreProxy = 'true' # ignore proxy # - $env:chocolateyProxyLocation = '' # explicit proxy # - $env:chocolateyProxyUser = '' # explicit proxy user name (optional) # - $env:chocolateyProxyPassword = '' # explicit proxy password (optional) # === NO NEED TO EDIT ANYTHING BELOW THIS LINE === # Ensure we can run everything Set-ExecutionPolicy Bypass -Scope Process -Force; # If the repository requires authentication, create the Credential object if ((-not [string]::IsNullOrEmpty($repoUsername)) -and (-not [string]::IsNullOrEmpty($repoPassword))) { $securePassword = ConvertTo-SecureString $repoPassword -AsPlainText -Force $repoCreds = New-Object System.Management.Automation.PSCredential ($repoUsername, $securePassword) } $searchUrl = ($packageRepo.Trim('/'), 'Packages()?$filter=(Id%20eq%20%27chocolatey%27)%20and%20IsLatestVersion') -join '/' # Reroute TEMP to a local location New-Item $env:ALLUSERSPROFILEchoco-cache -ItemType Directory -Force $env:TEMP = "$env:ALLUSERSPROFILEchoco-cache" $localChocolateyPackageFilePath = Join-Path $env:TEMP 'chocolatey.nupkg' $ChocoInstallPath = "$($env:SystemDrive)ProgramDataChocolateybin" $env:ChocolateyInstall = "$($env:SystemDrive)ProgramDataChocolatey" $env:Path += ";$ChocoInstallPath" $DebugPreference = 'Continue'; # PowerShell v2/3 caches the output stream. Then it throws errors due # to the FileStream not being what is expected. Fixes "The OS handle's # position is not what FileStream expected. Do not use a handle # simultaneously in one FileStream and in Win32 code or another # FileStream." function Fix-PowerShellOutputRedirectionBug { $poshMajorVerion = $PSVersionTable.PSVersion.Major if ($poshMajorVerion -lt 4) { try{ # http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ plus comments $bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField" $objectRef = $host.GetType().GetField("externalHostRef", $bindingFlags).GetValue($host) $bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetProperty" $consoleHost = $objectRef.GetType().GetProperty("Value", $bindingFlags).GetValue($objectRef, @()) [void] $consoleHost.GetType().GetProperty("IsStandardOutputRedirected", $bindingFlags).GetValue($consoleHost, @()) $bindingFlags = [Reflection.BindingFlags] "Instance,NonPublic,GetField" $field = $consoleHost.GetType().GetField("standardOutputWriter", $bindingFlags) $field.SetValue($consoleHost, [Console]::Out) [void] $consoleHost.GetType().GetProperty("IsStandardErrorRedirected", $bindingFlags).GetValue($consoleHost, @()) $field2 = $consoleHost.GetType().GetField("standardErrorWriter", $bindingFlags) $field2.SetValue($consoleHost, [Console]::Error) } catch { Write-Output 'Unable to apply redirection fix.' } } } Fix-PowerShellOutputRedirectionBug # Attempt to set highest encryption available for SecurityProtocol. # PowerShell will not set this by default (until maybe .NET 4.6.x). This # will typically produce a message for PowerShell v2 (just an info # message though) try { # Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48) # Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't # exist in .NET 4.0, even though they are addressable if .NET 4.5+ is # installed (.NET 4.5 is an in-place upgrade). [System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48 } catch { Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3+.' } function Get-Downloader { param ( [string]$url ) $downloader = new-object System.Net.WebClient $defaultCreds = [System.Net.CredentialCache]::DefaultCredentials if (Test-Path -Path variable:repoCreds) { Write-Debug "Using provided repository authentication credentials." $downloader.Credentials = $repoCreds } elseif ($defaultCreds -ne $null) { Write-Debug "Using default repository authentication credentials." $downloader.Credentials = $defaultCreds } $ignoreProxy = $env:chocolateyIgnoreProxy if ($ignoreProxy -ne $null -and $ignoreProxy -eq 'true') { Write-Debug 'Explicitly bypassing proxy due to user environment variable.' $downloader.Proxy = [System.Net.GlobalProxySelection]::GetEmptyWebProxy() } else { # check if a proxy is required $explicitProxy = $env:chocolateyProxyLocation $explicitProxyUser = $env:chocolateyProxyUser $explicitProxyPassword = $env:chocolateyProxyPassword if ($explicitProxy -ne $null -and $explicitProxy -ne '') { # explicit proxy $proxy = New-Object System.Net.WebProxy($explicitProxy, $true) if ($explicitProxyPassword -ne $null -and $explicitProxyPassword -ne '') { $passwd = ConvertTo-SecureString $explicitProxyPassword -AsPlainText -Force $proxy.Credentials = New-Object System.Management.Automation.PSCredential ($explicitProxyUser, $passwd) } Write-Debug "Using explicit proxy server '$explicitProxy'." $downloader.Proxy = $proxy } elseif (!$downloader.Proxy.IsBypassed($url)) { # system proxy (pass through) $creds = $defaultCreds if ($creds -eq $null) { Write-Debug 'Default credentials were null. Attempting backup method' $cred = get-credential $creds = $cred.GetNetworkCredential(); } $proxyaddress = $downloader.Proxy.GetProxy($url).Authority Write-Debug "Using system proxy server '$proxyaddress'." $proxy = New-Object System.Net.WebProxy($proxyaddress) $proxy.Credentials = $creds $downloader.Proxy = $proxy } } return $downloader } function Download-File { param ( [string]$url, [string]$file ) $downloader = Get-Downloader $url $downloader.DownloadFile($url, $file) } function Download-Package { param ( [string]$packageODataSearchUrl, [string]$file ) $downloader = Get-Downloader $packageODataSearchUrl Write-Output "Querying latest package from $packageODataSearchUrl" [xml]$pkg = $downloader.DownloadString($packageODataSearchUrl) $packageDownloadUrl = $pkg.feed.entry.content.src Write-Output "Downloading $packageDownloadUrl to $file" $downloader.DownloadFile($packageDownloadUrl, $file) } function Install-ChocolateyFromPackage { param ( [string]$chocolateyPackageFilePath = '' ) if ($chocolateyPackageFilePath -eq $null -or $chocolateyPackageFilePath -eq '') { throw "You must specify a local package to run the local install." } if (!(Test-Path($chocolateyPackageFilePath))) { throw "No file exists at $chocolateyPackageFilePath" } $chocTempDir = Join-Path $env:TEMP "chocolatey" $tempDir = Join-Path $chocTempDir "chocInstall" if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $file = Join-Path $tempDir "chocolatey.zip" Copy-Item $chocolateyPackageFilePath $file -Force # unzip the package Write-Output "Extracting $file to $tempDir..." if ($unzipMethod -eq '7zip') { $7zaExe = Join-Path $tempDir '7za.exe' if (-Not (Test-Path ($7zaExe))) { Write-Output 'Downloading 7-Zip commandline tool prior to extraction.' # download 7zip Download-File $7zipUrl "$7zaExe" } $params = "x -o`"$tempDir`" -bd -y `"$file`"" # use more robust Process as compared to Start-Process -Wait (which doesn't # wait for the process to finish in PowerShell v3) $process = New-Object System.Diagnostics.Process $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo($7zaExe, $params) $process.StartInfo.RedirectStandardOutput = $true $process.StartInfo.UseShellExecute = $false $process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden $process.Start() | Out-Null $process.BeginOutputReadLine() $process.WaitForExit() $exitCode = $process.ExitCode $process.Dispose() $errorMessage = "Unable to unzip package using 7zip. Perhaps try setting `$env:chocolateyUseWindowsCompression = 'true' and call install again. Error:" switch ($exitCode) { 0 { break } 1 { throw "$errorMessage Some files could not be extracted" } 2 { throw "$errorMessage 7-Zip encountered a fatal error while extracting the files" } 7 { throw "$errorMessage 7-Zip command line error" } 8 { throw "$errorMessage 7-Zip out of memory" } 255 { throw "$errorMessage Extraction cancelled by the user" } default { throw "$errorMessage 7-Zip signalled an unknown error (code $exitCode)" } } } else { if ($PSVersionTable.PSVersion.Major -lt 5) { try { $shellApplication = new-object -com shell.application $zipPackage = $shellApplication.NameSpace($file) $destinationFolder = $shellApplication.NameSpace($tempDir) $destinationFolder.CopyHere($zipPackage.Items(),0x10) } catch { throw "Unable to unzip package using built-in compression. Set `$env:chocolateyUseWindowsCompression = 'false' and call install again to use 7zip to unzip. Error: `n $_" } } else { Expand-Archive -Path "$file" -DestinationPath "$tempDir" -Force } } # Call Chocolatey install Write-Output 'Installing chocolatey on this machine' $toolsFolder = Join-Path $tempDir "tools" $chocInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1" & $chocInstallPS1 Write-Output 'Ensuring chocolatey commands are on the path' $chocInstallVariableName = 'ChocolateyInstall' $chocoPath = [Environment]::GetEnvironmentVariable($chocInstallVariableName) if ($chocoPath -eq $null -or $chocoPath -eq '') { $chocoPath = 'C:ProgramDataChocolatey' } $chocoExePath = Join-Path $chocoPath 'bin' if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) { $env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine); } Write-Output 'Ensuring chocolatey.nupkg is in the lib folder' $chocoPkgDir = Join-Path $chocoPath 'libchocolatey' $nupkg = Join-Path $chocoPkgDir 'chocolatey.nupkg' if (!(Test-Path $nupkg)) { Write-Output 'Copying chocolatey.nupkg is in the lib folder' if (![System.IO.Directory]::Exists($chocoPkgDir)) { [System.IO.Directory]::CreateDirectory($chocoPkgDir); } Copy-Item "$file" "$nupkg" -Force -ErrorAction SilentlyContinue } } # Idempotence - do not install Chocolatey if it is already installed if (!(Test-Path $ChocoInstallPath)) { # download the package to the local path if (!(Test-Path $localChocolateyPackageFilePath)) { Download-Package $searchUrl $localChocolateyPackageFilePath } # Install Chocolatey Install-ChocolateyFromPackage $localChocolateyPackageFilePath }
Install with Puppet
NOTE: If you have the licensed edition, see [[Setting up Licensed Edition with Puppet|Installation-Licensed#set-up-licensed-edition-with-puppet]] instead. This only additionally contains some package examples and setting up tab completion.
Here’s an example of setting Chocolatey up with Puppet that sets up and configures Chocolatey, sets up an internal package repository, and shows setting up the licensed edition and ensuring some packages.
- Download the chocolatey.nupkg from the community repository — download the latest chocolatey nupkg or see Completely offline install to get an older version.
- Optionally download the chocolatey.server package from the community repository — download the latest chocolatey.server nupkg.
- Use
choco push
to push those items to your internal package repository (e.g.choco push chocolatey.0.10.7.nupkg -s http://internal_repo/ -k abc123
) - Determine how to get the bare url to download the Chocolatey.Nupkg directly. You will need that for the internal url for installing Chocolatey offline. For the community repository, it is https://chocolatey.org/api/v2/package/chocolatey
# Requires puppetlabs/chocolatey module # See https://forge.puppet.com/puppetlabs/chocolatey ## Set resource defaults for `package` resources on Windows to use the Chocolatey provider case $operatingsystem { 'windows': { Package { provider => chocolatey, } } } ## - Ensure Chocolatey Install - #include chocolatey ## OR ## Download chocolatey.nupkg to your internal repository (see above ## about getting the package for offline use) ## Note: `chocolatey_download_url is completely different than normal ## source locations. This is directly to the bare download url for the ## chocolatey.nupkg, similar to what you see when you browse to ## https://chocolatey.org/api/v2/package/chocolatey class {'chocolatey': chocolatey_download_url => 'https://<internalurl/to>/chocolatey.nupkg', use_7zip => false, } ## If you need FIPS compliance ## make this the first thing you configure before you do any additional ## configuration or package installations #chocolateyfeature {'useFipsCompliantChecksums': # ensure => enabled, #} ## Keep chocolatey up to date based on your internal source ## You control the upgrades based on when you push an updated version ## to your internal repository. ## Note the source here is to the OData feed, similar to what you see ## when you browse to https://chocolatey.org/api/v2 package {'chocolatey': ensure => latest, provider => chocolatey, source => 'https://<internal_repo>/chocolatey', } ## - Configure Chocolatey - ### Config Settings ## Move cache location so Chocolatey is very deterministic about ## cleaning up temporary data chocolateyconfig {'cacheLocation': value => 'c:ProgramDatachoco-cache', } ## Increase timeout to 4 hours chocolateyconfig {'commandExecutionTimeoutSeconds': value => '14400', } ### Sources ## Remove the default community package repository source chocolateysource {'chocolatey': ensure => absent, location => 'https://chocolatey.org/api/v2/', } ## Add default sources for your internal repositories chocolateysource {'internal_chocolatey': ensure => present, location => 'http://internal_location/OData/endpoint', priority => 1, username => 'optional', password => 'optional,not ensured', } ### Features chocolateyfeature {'checksumFiles': ensure => enabled, } ## When using Puppet for installs chocolateyfeature {'showDownloadProgress': ensure => disabled, } chocolateyfeature {'useRememberedArgumentsForUpgrades': ensure => enabled, } ## - Chocolatey Simple Server Package Repository - ## Requires chocolatey/chocolatey_server module - see ## https://forge.puppet.com/chocolatey/chocolatey_server ## this contains the bits to install the custom server ## - Ensures IIS and Ensure ASP.NET ## - Installs and configures the Chocolatey.Server website and app pool ## - Sets permissions appropriately #include chocolatey_server ## OR ## `server_package_source` is to the OData feed, similar to what you see ## when you browse to https://chocolatey.org/api/v2 class {'chocolatey_server': server_package_source => 'https://internalurl/odata/server', } chocolateysource {'local_chocolatey_server': ensure => present, location => 'http://localhost/chocolatey', priority => 2, } ## - Tab Completion - ## Ensure that when someone uses choco from powershell.exe, they have tab completion file {'C:/Users/Administrator/Documents/WindowsPowerShell': ensure => directory, } file {'C:/Users/Administrator/Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1': ensure => file, content => '$ChocolateyProfile = "$env:ChocolateyInstallhelperschocolateyProfile.psm1" if (Test-Path($ChocolateyProfile)) { Import-Module "$ChocolateyProfile" }', } ## - Package Examples - package {'roundhouse': ensure => '0.8.5.0', } package {'git': ensure => latest, } ## see https://forge.puppet.com/puppetlabs/chocolatey#install-options-with-spaces package {'launchy': ensure => installed, install_options => ['--override', '--installArgs','"', '/VERYSILENT','/NORESTART','"'], } package {['virustotaluploader', 'googlechrome', 'notepadplusplus', '7zip', 'ruby', 'charles', 'grepwin', 'stexbar', 'inkscape', 'gitextensions', 'pandoc', 'snagit', 'nodejs', ]: ensure => latest, source => 'https://chocolatey.org/api/v2/', } package {'screentogif': ensure => '2.2.160907', source => 'https://chocolatey.org/api/v2/', } package {'dotnet4.5.2': ensure => latest, }
Install using PowerShell from cmd.exe
This is the best method if you want to repeat it or include it in source control. It requires no change to your existing PowerShell to allow for remote unsigned scripts.
Create a file named installChocolatey.cmd
with the following:
@echo off
SET DIR=%~dp0%
::download install.ps1
%systemroot%System32WindowsPowerShellv1.0powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "((new-object net.webclient).DownloadFile('https://chocolatey.org/install.ps1','%DIR%install.ps1'))"
::run installer
%systemroot%System32WindowsPowerShellv1.0powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& '%DIR%install.ps1' %*"
You can also get to this file by going to https://chocolatey.org/installchocolatey.cmd.
If you prefer to have the install.ps1 file already, comment out the download line in the batch file and download the install.ps1
from chocolatey.org and save it as install.ps1
next to the installChocolatey.cmd
file.
Run installChocolatey.cmd
from an elevated cmd.exe
command prompt and it will install the latest version of Chocolatey. You can not run this from powershell.exe
without making changes to your execution policy.
NOTE: To create and save a .cmd
file, please use a text editor and nothing fancy like Microsoft Word or OneNote.
Install using NuGet Package Manager
When you have Visual Studio 2010+ and the NuGet extension installed (pre-installed on any newer versions of Visual Studio), you can simply type the following three commands and you will have Chocolatey installed on your machine.
Install-Package chocolatey
Initialize-Chocolatey
Uninstall-Package chocolatey
Install using NuGet.exe from PowerShell
You can also use NuGet command line to download Chocolatey:
nuget install chocolatey
or nuget install chocolatey -pre
Once you download it, open PowerShell (remote unsigned), navigate to the tools folder and run:
& .chocolateyInstall.ps1
Install downloaded NuGet package from PowerShell
You can also just download and unzip the Chocolatey package (.nupkg
is a fancy zip file):
- Download the Chocolatey package.
- Ensure the downloaded nupkg is not blocked.
- Unzip it using any application that supports
zip
format. - Open a PowerShell command shell and navigate into the unzipped package’s tools folder.
- NOTE: Ensure PowerShell execution policy is set to at least bypass or remote signed (if you have issues, you may need to set it to Unrestricted).
- Call
& .chocolateyInstall.ps1
to allow Chocolatey to install. - NOTE: This will not set Chocolatey as an installed package, so it may be a good idea to also call
choco upgrade chocolatey -y
and let it reinstall the same version, but at least it will be available for upgrades then.
Install licensed edition
Please see [[installation of licensed edition|Installation-Licensed]].
Installing behind a proxy
Have a proxy? Try
- Cmd.exe:
@powershell -NoProfile -ExecutionPolicy Bypass -Command "[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH="%PATH%;%ALLUSERSPROFILE%chocolateybin"
- PowerShell.exe (Ensure Get-ExecutionPolicy is at least RemoteSigned):
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Installing behind an explicit proxy
See [[Installing Chocolatey Behind a Proxy Server|Proxy-Settings-for-Chocolatey#installing-chocolatey-behind-a-proxy-server]]
Installing to a different location
- Create a machine level (user level will also work) environment variable named
ChocolateyInstall
and set it to the folder you want Chocolatey to install to prior to installation (this environment variable must be set globally or available to PowerShell- it is not enough to simply make it available to your current command prompt session). - Don’t use
"C:Chocolatey"
unless necessary. - Create the folder manually.
- If you have already installed (and want to change the location after the fact):
- Follow the above steps.
- Install Chocolatey again.
- Copy/Move over the items from the old lib/bin directory.
- Delete your old install directory.
NOTE: There is one really important consideration when installing Chocolatey to a non-default location: Chocolatey only locks down the permissions to Admins when installed to the default location %PROGRAMDATA%Chocolatey
, which means the same thing as %SystemDrive%ProgramDataChocolatey
.
If you are installing to another location, you will need to handle this yourself, i. e. restrict write access to Admins in case you so desire.
This is due to alternative locations could have a range of permissions that should not be changed.
See [[Why does Chocolatey install where it does|DefaultChocolateyInstallReasoning]] and chocolatey/choco#398 for more details.
Installing a particular version of Chocolatey
Set the following environment variable prior to install:
chocolateyVersion
— controls what version of Chocolatey is installed
In PowerShell, it looks like this:
$env:chocolateyVersion = '0.9.9.12' # install script
NOTE: This will only work with the installation methods that call https://chocolatey.org/install.ps1 as part of the install.
Use Windows built-in compression instead of downloading 7zip
Set the following environment variable prior to install:
chocolateyUseWindowsCompression
— this will bypass the download and use of 7zip.
In PowerShell, it looks like this:
$env:chocolateyUseWindowsCompression = 'true' # install script
NOTE: This will only work with the installation methods that call https://chocolatey.org/install.ps1 as part of the install.
Installing with restricted TLS
NOTE: Chocolatey.org now requires TLS 1.2 at a minimum. Please see https://chocolatey.org/blog/remove-support-for-old-tls-versions.
NOTE: If your server is restricted to TLS 1.1+, you need to add additional logic to be able to download and install Chocolatey (this is not necessary when running Chocolatey normally as it does this automatically).
NOTE: If this is for organizational use, you should consider hosting the Chocolatey package internally and installing from there.
If you see an error that looks similar to the following:
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: An unexpected error occurred on a receive." At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/in ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException
OR:
Exception calling "DownloadString" with "1" argument(s): "The request was aborted: Could not create SSL/TLS secure channel." At line:1 char:51 + ... ess -Force; iex ((New-Object System.Net.WebClient).DownloadString('ht ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException
It’s possible that you are attempting to install from a server that needs to use TLS 1.1 or TLS 1.2 (has restricted the use of TLS 1.0 and SSL v3), you have some options. Chocolatey.org now requires TLS 1.2 at a minimum.
Option 1 — Host Internally
If you are an organization, this is your best option and it reduces issues with rate limiting that could occur later.
See https://chocolatey.org/install#organization for details.
Option 2 — Updated PowerShell and .NET
Upgrade to the following:
- PowerShell v3+
- .NET Framework 4.5
try { # Set TLS 1.2 (3072) as that is the minimum required by Chocolatey.org # Use integers because the enumeration value for TLS 1.2 won't exist # in .NET 4.0, even though they are addressable if .NET 4.5+ is # installed (.NET 4.5 is an in-place upgrade). [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 } catch { Write-Warning 'Unable to set PowerShell to use TLS 1.2. This is required for contacting Chocolatey as of 03 FEB 2020. https://chocolatey.org/blog/remove-support-for-old-tls-versions. If you see underlying connection closed or trust errors, you may need to do one or more of the following: (1) upgrade to .NET Framework 4.5+ and PowerShell v3+, (2) Call [System.Net.ServicePointManager]::SecurityProtocol = 3072; in PowerShell prior to attempting installation, (3) specify internal Chocolatey package location (set $env:chocolateyDownloadUrl prior to install or host the package internally), (4) use the Download + PowerShell method of install. See https://chocolatey.org/docs/installation for all install options.' } iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Option 3 — Manual
You need to download and unzip the Chocolatey package, then call the PowerShell install script from there. See the Download + PowerShell Method section below.
Non-Administrative install
NOTE: This option should be a last resort and is considered to be a more advanced scenario — most things you do on Windows require administrative rights, especially surrounding software management, so you are going to be limited even in packages you attempt to install. If you are using the community package repository, there are over 200 packages you can install from the community repository without administrative permission — see https://chocolatey.org/packages?q=id%3Aportable+tag%3Aportable.
You must choose a different location than the default (see Installing to a different location above). The default is a more secure location that only administrators can update.
- Save the script below as
ChocolateyInstallNonAdmin.ps1
. - Use the script below, determine where you might want Chocolatey installed if it is not to
C:ProgramDatachocoportable
. - Open PowerShell.exe.
- Run the following
Set-ExecutionPolicy Bypass -Scope Process -Force;
- Run
.ChocolateyInstallNonAdmin.ps1
.
ChocolateyInstallNonAdmin.ps1:
# Set directory for installation - Chocolatey does not lock # down the directory if not the default $InstallDir='C:ProgramDatachocoportable' $env:ChocolateyInstall="$InstallDir" # If your PowerShell Execution policy is restrictive, you may # not be able to get around that. Try setting your session to # Bypass. Set-ExecutionPolicy Bypass -Scope Process -Force; # All install options - offline, proxy, etc at # https://chocolatey.org/install iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Examples of packages you can install:
choco install puppet-agent.portable -y choco install ruby.portable -y choco install git.commandline -y # pick an editor #choco install visualstudiocode.portable -y # not yet available choco install notepadplusplus.commandline -y #choco install nano -y #choco install vim-tux.portable # What else can I install without admin rights? # https://chocolatey.org/packages?q=id%3Aportable
If you prefer or need cmd.exe example, please see https://gist.github.com/ferventcoder/78fa6b6f4d6e2b12c89680cbc0daec78
Upgrading Chocolatey
Once installed, Chocolatey can be upgraded in exactly the same way as any other package that has been installed using Chocolatey. Simply use the command to upgrade to the latest stable release of Chocolatey:
Uninstalling Chocolatey
See [[uninstall|Uninstallation]].
FAQs
I’m having trouble installing Chocolatey
Make sure you’ve reviewed More Install Options and looked over [[Troubleshooting|Troubleshooting]]. If you’ve done those things, reach out over the mailing list or over the chat (Gitter). The links to those can be found in the open source section of https://chocolatey.org/support.
I’m getting a 403 attempting to install
This is addressed in [[Troubleshooting|Troubleshooting]].
Why isn’t there an MSI?
tl;dr — Chocolatey installs as a nupkg like everything else, a PowerShell install script just ensures that.
Chocolatey was born out of providing automation for Windows and doing that with packages, packages that could surround an installer but didn’t necessarily need to. The Chocolatey install scripts use the Chocolatey package (a nupkg file itself) to be installed and upgraded as just another package. This means Chocolatey is «eating its own dogfood» and it is unlikely we’d offer it as an MSI (native installer)as it would fly a bit in the face of what Chocolatey represents (although it is something that we would not rule out).
The installation actually ensures a couple of things:
-
PowerShell is installed and is set up properly.
PowerShell is a requirement for using Chocolatey, not just for install. It is what drives the package installation process in most cases. Every package can have binaries and/or installation/uninstallation scripts (written in PowerShell). Chocolatey is the framework and each package gets to define how it is installed, upgraded, and uninstalled. It’s an extremely flexible framework that has been proven to meet the insanity that is the Windows software installation ecosystem. That flexibility would not be easily achieved without PowerShell.
We do recognize there are a few organizations that disable PowerShell, so it’s very likely in the future our Business Edition will meet that need. PowerShell is a staple of Windows automation, so it is not the norm for an organization in this day and age to disable PowerShell.
Having an install process that uses PowerShell helps you determine quickly if Chocolatey will be able to be used in your environment.
-
You are open to doing things in a slightly different way, e.g. working with packages as opposed to installers.
You are open to the concept of using packages. Some folks might say this means we are asking folks to learn to ‘do things «our way» because we know better’. It’s less about «knowing better» and more about learning that Chocolatey does things in a slightly different way. It does that because the world of software is not just installers. Software goes beyond Programs and Features and a system that can track all of that also needs to as well. Package management is not a new concept in the world of software, perhaps just newer to Windows. If folks are not open to that, then they are probably not going to be open to Chocolatey. And that’s completely fine. Chocolatey is not for everyone. We may eventually get to more of a masses approach. Right now we are targeting a specific type of audience — those that are looking for better ways to manage software on Windows and open to looking for the best process of doing that.
Before you begin this guide you’ll need the following:
- Internet Connection.
Please follow the below steps in order to install Chocolatey on your windows 7 Machine.
- Open an administrative command prompt as an Administrator.
Note: If you not aware as how to open the command prompt as an Administrator,Please follow these steps.
-
Click on the Windows Icon
- Right click on Windows Command Processor, Select and Click on Run as Administrator.
-
If User Account Control dialog opens Click Yes.
Now you have opened command prompt successfully as an administrator.
-
Navigate to the URL: https://chocolatey.org/
-
Click on Install.
-
Click on More Options under More Install Options
-
Click on the Copy Icon image next to Cmd.exe-
@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin
Note:It copies the code needed to invoke on command line.
-
Switch back to command prompt.
-
Paste the code which you just copied earlier.
@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin
-
Hit Enter on your keyboard.
-
It downloads the Chocolatey and adds to the Windows Path system C:ProgramDatachocolateybin and it is ready to use.
Since chocolatey is installed in our machine.Let us try to Install CC Cleaner as a demo with the help of using chocolatey.
Follow these steps:
-
Navigate to https://chocolatey.org/packages
-
From the search box search for CCleaner
At the time of writing this tutorial the latest version of CCleaner was 5.20.5668. You might see a new version now.
-
Copy the code :
Do not copy C:> which is infront of the code.
-
Switch back to command prompt and paste the code which you just copied.
-
Hit Enter.
Installation starts…
-
Type Y and hit Enter.
-
The install of ccleaner was successful message appears.
Congratulations!
Пользователям Linux привычна установка, удаление и обновление приложений с помощью менеджера пакетов apt-get — это безопасный и удобный способ быстро установить то, что нужно. В Windows 7, 8 и 10 можно получить аналогичные функции благодаря использованию менеджера пакетов Chocolatey и именно об этом пойдет речь в статье. Цель инструкции — познакомить обычного пользователя с тем, что такое менеджер пакетов и показать преимущества использования данного подхода.
Обычный способ установки программ на компьютер для пользователей Windows — скачать программу из Интернета, после чего запустить установочный файл. Все просто, но есть и побочные эффекты — установка дополнительного ненужного ПО, дополнений браузера или изменение его настроек (все это может быть и при установке с официального сайта), не говоря уж о вирусах при загрузке с сомнительных источников. Кроме этого, представьте, что вам нужно установить сразу 20 программ, хотелось бы как-то автоматизировать этот процесс? Примечание: Windows 10 включает в себя собственный менеджер пакетов OneGet (Использование OneGet в Windows 10 и подключение репозитория Chocolatey), также в 2020-м был представлен диспетчер пакетов Winget.
Установка Chocolatey
Для установки Chocolatey на компьютер, вам потребуется запустить командную строку или Windows PowerShell от имени администратора, после чего использовать следующие команды:
В командной строке
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin
В Windows PowerShell используйте команду Set-ExecutionPolicy RemoteSigned для разрешения выполнения удаленных подписанных сценариев, после чего установите Chocolatey с помощью команды
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
После установки через PowerShell перезапустите его. Вот и все, менеджер пакетов готов к работе.
Используем менеджер пакетов Chocolatey в Windows
Для того, чтобы скачать и установить любую программу с использованием менеджера пакетов, вы можете использовать командную строку или Windows PowerShell, запущенные от имени администратора. Для этого вам достаточно всего лишь ввести одну из команд (пример для установки Skype):
- choco install skype
- cinst skype
При этом, будет автоматически загружена и установлена последняя официальная версия программы. Более того, вы не увидите предложений согласиться на установку нежелательного ПО, расширений, изменения поиска по умолчанию и стартовой страницы браузера. Ну и последнее: если вы укажите через пробел несколько названий, то все они будут по очереди установлены на компьютер.
В настоящий момент таким образом можно установить около 3000 бесплатных и условно бесплатных программ и, естественно, вы не можете знать названия всех из них. В этом случае вам поможет команда choco search.
К примеру, если попробовать установить браузер Mozilla, то вы получите сообщение об ошибке, что такая программа не найдена (еще бы, ведь браузер называется Firefox), однако choco search mozilla позволит понять в чем ошибка и следующим шагом достаточно будет ввести cinst firefox (номер версии указывать не требуется).
Отмечу, что поиск работает не только по названиям, но и по описанию доступных приложений. Например, для поиска программы записи дисков, можно поискать по ключевому слову burn, и в результате получить список с нужными программами, включая те, в названии которых burn не фигурирует. Полный список доступных приложений вы можете посмотреть на сайте chocolatey.org.
Аналогичным образом можно удалить программу:
- choco uninstall имя_программы
- cuninst имя_программы
или обновить ее с помощью команд choco update или cup. Вместо имени программы можно использовать слово all, то есть choco update all обновит все программы, установленные с помощью Chocolatey.
Графический интерфейс менеджера пакетов
Имеется возможность использовать и графический интерфейс Chocolatey для установки, удаления, обновления и поиска программ. Для этого введите choco install ChocolateyGUI и запустите установленное приложение от имени Администратора (появится в меню пуск или списке установленных программ Windows 8). Если вы планируете часто им пользоваться, рекомендую отметить запуск от имени Администратора в свойствах ярлыка.
Интерфейс менеджера пакетов интуитивно понятен: две вкладки, с установленными и доступными пакетами (программами), панель с информацией о них и кнопками для обновления, удаления или установки, в зависимости от того, что именно было выбрано.
Преимущества данного способа установки программ
Подводя итог, еще раз отмечу преимущества использования менеджера пакетов Chocolatey для установки программ (для начинающего пользователя):
- Вы получаете официальные программы из надежных источников и не рискуете, пытаясь найти то же ПО в Интернете.
- При установке программы не требуется следить за тем, чтобы не установилось чего-либо ненужного, будет установлено чистое приложение.
- Это действительно быстрее, чем поиск официального сайта и страницы загрузки на нем вручную.
- Вы можете создать файл сценария (.bat, .ps1) или просто установить сразу все нужные бесплатные программы одной командой (например, после переустановки Windows), то есть для установки двух десятков программ, включая антивирусы, утилиты и проигрыватели, вам нужно лишь один раз ввести команду, после чего даже не понадобиться нажимать кнопку «Далее».
Надеюсь, кому-то из моих читателей эта информация будет полезной.
In this article will show how to install programs and packages from the Command Prompt/Power shell on Windows operating system using Chocolatey – The package manager for Windows
The Linux distributions come with a package manager, which is a powerful tool for most power users to install, update and remove packages, directly from the command line or terminal. While most users are not comfortable with the interface of the command line or Terminal on Linux distributions, it is undeniably a great tool, if you know how to use it. On the other hand, Windows users enjoy the graphical user interface to install, update and uninstall programs and packages, which isn’t unified for all the programs you use regularly. Even though it is easy to manage programs on Windows in the user-friendly GUI, you should keep a constant tab to prevent the installer from installing any malware or unnecessary programs.
Considering likes and dislikes for the Terminal and the GUI to be a relative aspect, the good side is, you can even install programs on your Windows computer using the command line, just the way you do it on Linux-based operating systems or Linux distributions. As Windows doesn’t have native support for installing programs directly from the Command Prompt, you will have to use third-party software to enable this feature on Windows. Don’t worry. It isn’t going to cost you an arm and a leg, nor it is going to be too challenging.
So without further delay, let’s get started with how you can start installing apps on Windows directly from the Command Prompt or PowerShell, whichever is convenient for you.
The minimum requirements to install Chocolatey package manager
- You should be running Windows 7 or Windows 2003 or any other later version of Windows along with PowerShell v2 or any later version to use Chocolatey.
- .NET Framework 4 or better should also be installed on your computer.
So that was all about the minimum requirements to run Chocolatey on your Windows computer.
Ways to install Chocolatey Packages on Windows
Using Command Prompt
Step 1: Open Command Prompt
Press ‘Win + R’ and type ‘cmd’. Now press the key combination ‘Ctrl + Shift + Enter’ to open Command Prompt with administrator permissions.
Now type in the following command, and hit the enter key to execute the same.
@"%SystemRoot%System32WindowsPowerShellv1.0powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%chocolateybin"
Step 2: Download and install Chocolatey
Let Command Prompt download and install Chocolatey for you. You will get the following screen, and once the installation is complete, you can get back the prompt to enter the subsequent commands.
#Using Windows PowerShell to install Chocolatey
Step 1: Using PowerShell
Open Windows PowerShell with administrator rights by right-clicking on the Start menu and by clicking on ‘Windows PowerShell (Admin)’.
Now type in the following command to install Chocolatey using Windows PowerShell.
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Wait for the download and installation process to be complete, and once it is complete, you can get back the prompt to enter a command and carry out your work.
The installation of Chocolatey using Command Prompt or Windows PowerShell is complete now.
I would recommend you to restart your computer before you carry out any real activity using Chocolatey.
Now open Command Prompt, and you can search for, install, update, and uninstall programs directly from the Command Prompt.
Some useful Chocolatey commands
Let’s find out some useful commands that can be handy for you while you are using Chocolatey. The commands aren’t platformed specific, and you can use the command on both Command Prompt and Windows PowerShell. But make sure, you are executing the commands with the administrator privileges.
- Getting help: choco -?
- Searching for programs: choco search <app/package_name>
- Installing programs: choco install <app/package_name>
- Updating programs: choco update <app/package_name>
- Uninstalling programs: choco uninstall <app/package_name>
- Updating Chocolatey: choco update chocolatey
There are hundreds of command available for Choco, and you can even use additional arguments with all the commands, however, you will not need to add extra arguments for if you are using it for personal usage. It can also be a tough job to remember the arguments, so nevermind. But if your friends call you a geek, and you are a confident power user, the extra arguments can surely come in handy once in a while. Here are the additional commands to use Chocolatey.
How to use Chocolatey command to download software packages
An example
Chocolatey is super easy to use. Just search for the program, and install it effortlessly with just the command. So let me search for Vivaldi browser, and install it on my system.
Type the following command to search for the keyword Vivaldi, in the packages, which Chocolatey has access to.
choco search vivaldi
Now you will have to install Vivaldi on your system using the ‘install’ command.
Type in the following command to install Vivaldi.
choco install vivaldi
It isn’t necessary to install the complete package name. Just type in the name of the program or package, and leave the rest to Chocolatey.
The installation will start immediately, and meanwhile, you will be asked, whether you want to execute the script to download and install Vivaldi. Just type in Y, N, P respectively followed by the enter key to allow execution, prevent execution, and print the script respectively.
Needless to say, you need to enter ‘Y’ for installing Vivaldi. You will get the following screen, as long as the download and installation process goes on.
Once the installation is complete, you will get back the prompt.
Vivaldi will now be automatically available on your desktop.
Just open it to start using Vivaldi, just the way you do it for other programs on Windows.
How To Upgrade Chocolatey
Just in Command Prompt or Power shell of the Windows 10/8/7 use the below-given command.
choco upgrade chocolatey
How to uninstall Chocolatey installed Packages
To uninstall Vivaldi now, just type in the following command followed by hitting the enter key.
choco uninstall vivaldi
Now you will have to choose the version of Vivaldi, which you want to uninstall. I want to uninstall all the versions of Vivaldi, and thus, I will choose 4, and hit the enter key.
You will again be asked, whether you want to execute the script. Just type ‘Y’ and hit the enter key to execute the script and delete Vivaldi.
Vivaldi will not be uninstalled from your system. Depending upon which program you are uninstalling, you might be asked for a GUI-based confirmation to uninstall the program. You might even use additional arguments to force uninstall programs, the provision for which, is also available on Chocolatey.
Chocolatey is undoubtedly a powerful tool to manage programs and packages effortlessly on Windows. There are hundreds of programs, which you can download and install, using Chocolatey. Chocolatey is a kind of repository just like Linux, where you can download all your programs with just a single command. However I will never compare the power of Chocolatey repository with the apt repository for Linux, as both are meant for two different platforms, and availability will undoubtedly vary on the two.platforms.
With Chocolatey, you will not even need to enter the full name of the package, which is cool, as well. I searched for some random less well-known programs, most users haven’t heard about and I was amazed to see some results turn up. I am sure, the database of programs will keep expanding in the coming days. Chocolatey can be considered as a command line alternative for Ninite on Windows, which can help you install multiple selected programs in one go.
Chocolatey is open-source, though there are personal and business editions available, and you can see their prices here. You will no longer have to worry about automatic updates slowing down your internet connection, your computer or both, as you can update the programs and packages whenever you want, directly from the Command Prompt.
How cool was that! I know you will thank me later for this. Hope the information was useful for you. Do you have any additional questions? Feel free to comment the same down below.
- How to install ADB on Windows 10,8, 7 and Linux, the easiest way
- Download & install npm and node.js packages on Windows 10/8/7
- How to install Gimp on Ubuntu via command terminal
- Tutorial Install and use Node.js http-server (Web server) via NPM
- How to proceed with the Python Canopy installation steps, on Windows and Linux?
- Install Node js on Ubuntu 19.04
- Install Grunt on Windows 10/8/7