- Использование Chocolatey для установки программ в Windows
- Установка Chocolatey
- Используем менеджер пакетов Chocolatey в Windows
- Графический интерфейс менеджера пакетов
- Преимущества данного способа установки программ
- Setup / Install
- 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
- I’m having trouble installing Chocolatey
- I’m getting a 403 attempting to install
- Why isn’t there an MSI?
Использование Chocolatey для установки программ в Windows
Пользователям Linux привычна установка, удаление и обновление приложений с помощью менеджера пакетов apt-get — это безопасный и удобный способ быстро установить то, что нужно. В Windows 7, 8 и 10 можно получить аналогичные функции благодаря использованию менеджера пакетов Chocolatey и именно об этом пойдет речь в статье. Цель инструкции — познакомить обычного пользователя с тем, что такое менеджер пакетов и показать преимущества использования данного подхода.
Обычный способ установки программ на компьютер для пользователей Windows — скачать программу из Интернета, после чего запустить установочный файл. Все просто, но есть и побочные эффекты — установка дополнительного ненужного ПО, дополнений браузера или изменение его настроек (все это может быть и при установке с официального сайта), не говоря уж о вирусах при загрузке с сомнительных источников. Кроме этого, представьте, что вам нужно установить сразу 20 программ, хотелось бы как-то автоматизировать этот процесс? Примечание: Windows 10 включает в себя собственный менеджер пакетов OneGet (Использование OneGet в Windows 10 и подключение репозитория Chocolatey), также в 2020-м был представлен диспетчер пакетов Winget.
Установка Chocolatey
Для установки Chocolatey на компьютер, вам потребуется запустить командную строку или Windows PowerShell от имени администратора, после чего использовать следующие команды:
В командной строке
В Windows PowerShell используйте команду Set-ExecutionPolicy RemoteSigned для разрешения выполнения удаленных подписанных сценариев, после чего установите Chocolatey с помощью команды
После установки через 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), то есть для установки двух десятков программ, включая антивирусы, утилиты и проигрыватели, вам нужно лишь один раз ввести команду, после чего даже не понадобиться нажимать кнопку «Далее».
Надеюсь, кому-то из моих читателей эта информация будет полезной.
А вдруг и это будет интересно:
Почему бы не подписаться?
Рассылка новых, иногда интересных и полезных, материалов сайта remontka.pro. Никакой рекламы и бесплатная компьютерная помощь подписчикам от автора. Другие способы подписки (ВК, Одноклассники, Телеграм, Facebook, Twitter, Youtube, Яндекс.Дзен)
03.11.2014 в 22:04
Вечер добрый, отличная статья, но хотелось бы увидеть хотя бы маленький пример батника на 2 — 3 программы, сам просто могу писать бат файлы только по приблизительным примерам.
05.11.2014 в 08:31
Здравствуйте. Сделайте обычный текстовый файл, на каждой строке пишите по команде, никаких знаков препинания не нужно. То есть к примеру:
choco install skype
choco install recuva
Также должен работать и вариант с choco install skype recuva в одной единственной строке, но тут я не пробовал сразу с десяток программ вписать.
Дополнительно, если планируете использовать на чистом компьютере, можете в первую строку вписать команду для установки самого Chocolatey.
29.12.2014 в 00:42
Доброго времени суток!
У меня после установки через ком. строку или PowerShell, при попытке выполнить какую-либо команду (choco search, choco install ChocolateyGUI) появляется надпись — PowerShell не является внутренней или внешней командой, исполняемой программой или пакетным файлом.
И дальше ничего не сделать. В чем может быть проблема?
29.12.2014 в 08:38
Здравствуйте. Поищите в сети по тексту ошибки, в одном из первом результатов есть решение. А причины появления ошибки у вас я не знаю. Но скорее всего, вам либо требуется установить переменную PATH %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\ (опять же, в интернете найдите, как установить системную переменную PATH в Windows), либо, возможно, вы не задали Execution Policy (об этом есть в текущей статье).
14.01.2015 в 23:54
Здравствуйте. У меня при попытке установить любую программу выдаёт ошибку Write Error. Как это можно исправить? Спасибо заранее.
16.01.2015 в 09:28
Запускаете от администратора? Права доступа ко всем дискам есть?
29.04.2015 в 11:04
Добрый день!
А можно узнать, как программа определяет пути, по которым нужно скачивать файлы программ? дело в том, что мне нужно скачивать сами дистрибутивы, без их последующей установки. Можно ли как-то добиться этого? Пытался найти на оф.сайте пути к ftp программ, но также не нашел.
Пример:
Installing the following packages:
flashplayerplugin
By installing you accept licenses for the packages.
flashplayerplugin v17.0.0.134
Downloading flashplayerplugin 32 bit
from download.macromedia.com/get/flashplayer/current/licensing/win/in
stall_flash_player_17_plugin.msi
Installing flashplayerplugin…
flashplayerplugin has been installed.
Всё самое важное для меня — в строке download.macromedia.com/get/flashplayer/current/licensing/win/in
stall_flash_player_17_plugin.msi
30.04.2015 в 09:13
Программа ищет и берет соответствующий файл скрипта .ps1 из репозитория (онлайн), в нем и указан адрес. Посмотрел по командам и передаваемым параметрам, не нашел возможности скачивать без установки (хотя, думаю, должна быть, плохо искал). Один из способов получить ссылки на установщики, хоть и не вполне удобный, зайти в галерею packages на chocolatey.org, потом выбрать нужное ПО и на его странице в разделе Files нажать Show, вы увидите тот самый скрипт ps1, в котором есть ссылка на источник.
18.03.2016 в 20:46
Здравствуйте! Как правильно удалить Chocolatey, если я не хочу им пользоваться? Просто грохнуть папку C:\ ProgramData\ chocolatey будет не очень верным решением, наверно?
19.03.2016 в 07:39
Здравствуйте.
Это как раз верное решение.
1) удаляем папку
2) удаляем переменные среды, которые были созданы Chocolatey (Система — дополнительные параметры системы — вкладка дополнительно — переменные среды). Что именно он там создает уже не помню, но в официальном гайде написано, что нужно удалить.
09.05.2016 в 00:19
ненужная притом. Кто будет вносить и записывать себе список программ если через 5-6 лет они 100 раз поменяются. Да и вообще другие могут быть. Если тот вася который винду переустанавливает каждый месяц — то да.
Но всеравно. ибо ждать пока несколько гиг с инета загрузится — воще не вариант. было бы здорово если бы можно было скачать пакеты вручную и устанавливать с готовой папки.
Тогда ваще кул. можно сделать батник для установки клиентам если переустановкой системы занимаешся. Пришел с флехей. запустил батник и пошел на 10 мин пить кофе. А так с инета вообще не вариант.
не в курсе как сделать чтобы с локальной папки инсталы брались? И где папка должна быть? и куда к ней пути прописать?
09.05.2016 в 07:22
Насчет с локальной папки — не в курсе. По идее вручную скрипт написать и где-то достать установщиков с возможностью «тихой» установки.
Но минус такого подхода — версии не те софта будут, а с менеджерами пакетов — последние.
А так, из того что попроще — вон installpack русский сейчас двигают, посмотрите.
02.08.2016 в 20:09
В одном из филиалов на серваке с файловой помойкой сделал репозиторий по инструкции rahmanny.blogspot.ru/2016/01/windows.html
Установка и обновление софта производится через логон скрипты. В принципе удобно и не нужно разворачивать Sccm
03.12.2017 в 22:33
Здравствуйте, не подскажите, у вас есть какие-нибудь обзоры программ для автоматического выполнения действий на компьютере. Которые записывают действия мыши и клавиатуры и потом повторяют. По поиску у вас нашел только это. Может что-то посоветуете. Спасибо.
04.12.2017 в 09:10
Здравствуйте. Нет, такого нету у меня. И какого-то четкого совета дать не могу, так как сам никогда не пользовался подобным.
15.10.2020 в 15:11
Пожалуйста обновите статью так как очень мало информации на русском языке по данной программе, спасибо
Setup / Install
Requirements
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 or choco -? now, or see Getting Started for usage instructions.
Install with cmd.exe
Run the following command:
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 returns Restricted , then run Set-ExecutionPolicy AllSigned or Set-ExecutionPolicy Bypass -Scope Process .
- Now run the following command:
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
Troubleshooting? Proxy? Need more options?
More Install Options
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 returns Restricted , then run Set-ExecutionPolicy AllSigned or Set-ExecutionPolicy Bypass .
- Now run the following command:
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).
Install with Puppet
📝 NOTE If you have the licensed edition, see Setting 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
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:
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:
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).
📝 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
Installing behind a proxy
Have a proxy? Try
Installing behind an explicit proxy
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%\ProgramData\Chocolatey . 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 and GitHub Issue 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:
📝 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:
📝 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 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:
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.
Option 2 — Updated PowerShell and .NET
Upgrade to the following:
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:\ProgramData\chocoportable .
- Open PowerShell.exe.
- Run the following Set-ExecutionPolicy Bypass -Scope Process -Force;
- Run .\ChocolateyInstallNonAdmin.ps1 .
Examples of packages you can install:
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
I’m having trouble installing Chocolatey
Make sure you’ve reviewed More Install Options and looked over 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.
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.