Использование chocolatey для установки программ в windows

Как использовать менеджер пакетов Chocolatey в Windows для установки, поиска и удаления программ в командной строке. Подробная инструкция для начинающих.

Comparison

How is Chocolatey different than NuGet and/or OpenWrap?

Chocolatey is a machine package manager. Where NuGet/OW are focused on developer library packages, Chocolatey is focused on applications and tools, and not necessarily developer focused.

A typical way of stating the difference is «Developers use NuGet to get 3rd party libraries that they use to build the .NET tools and applications that they release with Chocolatey!»

How is/will Chocolatey be different than apt?

  • Library packages are not completely off the plate, but mostly. How would you link the library up to the application/tool?

Packaging

Tell me about packaging

Chocolatey packages are what we like to think of as just fancy zip files. Zip files that have package metadata about the package and the underlying software a package may represent, dependencies, and optional binaries, files, and/or optional PowerShell automation scripts.

How do I create packages?

Try running from a command shell and inspect the output. You will find quite a bit of helpful information and just in time documentation in there.

I’m creating packages with the software contained in the package.

Great! This is the most reliable use of Chocolatey, to embed the binaries directly in the package. See the next question for more details.

I’m creating internal or offline packages, what do I need?

Well, if you are not creating packages for the community package repository, you have different rules that apply. Embed as much as possible into the package (as long as it is under 500MB you should see no issues). We typically recommend 500MB as the threshhold for organizations for the following reasons:

  • a nupkg file size takes up some space
  • files in the package directory (can be cleaned up as part of the script)
  • the actual install location if using an installer
  • MSI cache for MSIs — Windows caches the complete MSI binaries (and now you know where all that space went)

Установка приложений из репозитория Chocolatey

Рассмотрим теперь, как установить приложение (пакет) из репозитория Chocolatey.

Список доступных для установки приложения можно получить непосредственно на официальном веб сайте Chocolatey (https://chocolatey.org/packages)

Также  можно найти и установить нужное приложение прямо из консоли PowerShell. Например, для просмотра pdf файлов нам понадобилось установить приложение Adobe Acrobat Reader. Т.к. мы не знаем полного названия приложения, для его установки нам нужно получить имя пакета в каталоге. Выполним поиск в репозитории по ключевому слову ‘adobe’:

В консоли появится список всех пакетов по данному ключу. Нам нужен пакет  adobereader (нужно использовать именно имя пакета из столбца Name).

Запускаем установку пакета Adobe Reader:

Вверху окна PowerShell появится ползунок, свидетельствующий о начале загрузки пакета Adobe Reader. Сразу после окончания загрузки, приложение установится в системе.

Еще один пример. Допустим, нам понадобилось иметь на компьютере набор утилит SysInternals. Чтобы не качать его вручную, найдем пакет SysInternals в репозитарии Chocolatey и установим его.

Т.к. пакет не требует установки, он сохраняется на компьютер и хранится в каталоге C:\Chocolatey\lib\. В нашем примере это каталог C:\Chocolatey\lib\sysinternals.2016.11.18\tools

Сразу несколько приложений можно установить всего одной командой:

How does Chocolatey work?

How the heck does this all work?

Installation

  1. Choco determines if it is self-contained or has automation scripts — PowerShell scripts (*.ps1 files) and possibly other formats at a later date.
  2. Choco takes a registry snapshot for later comparison.
  3. If there are automation scripts, choco will run those. They can contain whatever you need to do, if they are PowerShell you have the full power of Posh (PowerShell), but you should try to ensure they are compatible with Posh v2+ (PowerShell v2 and beyond).
  4. Choco compares the snapshot and determines uninstaller information and saves that to a .registry file.
  5. Choco snapshots the folder based on all files that are currently in the package directory.
  6. Choco looks for executable files in the package folder and generates shims into the folder so those items are available on the path. Those could have been embedded into the package or brought down from somewhere (internet, ftp, file folder share, etc) and placed there. If there is a shim ignore file , then Chocolatey will not generate a shim in the bin folder.

Upgrade

  1. Starting in 0.9.10, Chocolatey will look for and run a chocolateyBeforeModify.ps1 file in the existing package prior to upgrading or uninstalling a package. This is your opportunity to shut down services and/or processes. This is run from the existing package, not the new version of the package. If it fails, it just passes a warning and continues on.
  2. Similar to install, except choco will make a backup of the package folder (and only the package folder) prior to attempting upgrade.
  3. The files snapshot is used to determine what files can be removed from the package folder. If those files have not changed, they will be removed.
  4. If the upgrade fails, choco will ask if you want to rollback the package folder to the previous version. If you choose to move roll back, it will put the backed up package directory back in place. This does not fix any folders you may have been using outside of the package directory, such as where the native installer may have installed a program to nor the location of / (e.g. ). You will need to handle those fixes on your own. Chocolatey also doesn’t rerun any install scripts on rollback.

Uninstall

  1. Choco makes the determination that the package is actually installed.
  2. Starting in 0.9.10, Chocolatey will look for and run a chocolateyBeforeModify.ps1 file in the existing package prior to upgrading or uninstalling a package. This is your opportunity to shut down services and/or processes. If it fails, it just passes a warning and continues on.
  3. Choco will make a backup of the package folder.
  4. The automation script is run if found. This should be used to clean up anything that is put there with the install script.
  5. If auto uninstaller is turned on, choco will attempt to run the auto uninstaller if a silent uninstall can be determined. Otherwise it will prompt the user (unless -y) to ask if they want the uninstaller to continue. The auto uninstaller can automatically detect about 80% of the different native uninstallers and determine or use the silent uninstall arguments.
  6. If everything is successful so far, the files snapshot is used to determine what files can be removed from the package folder. If those files have not changed, they will be removed.
  7. If everything is deleted from the package folder, the folder is also removed.

Что такое Chocolatey

Chocolatey – это консольная программа, с помощью которой можно устанавливать, обновлять и удалять программы в операционной системе Windows.

По логике своей работы Chocolatey похожа на менеджеры пакетов, применяющиеся в Linux. Вы просто вводите команду установки и указываете программу, которую требуется установить, после чего все устанавливается автоматически и очень быстро. Вам не нужно кликать мышкой «Next» и принимать пользовательские соглашения, как это происходит в обычных установщиках с графическим интерфейсом. При этом Chocolatey умеет устанавливать зависимости, поэтому если какой-то программе нужны дополнительные модули, то они будут установлены автоматически. Обновление и удаление через Chocolatey также выполняется всего одной командой.

Chocolatey имеет собственный репозиторий программ, который поддерживается сообществом. При установке файлы автоматически скачиваются с этого репозитория, поэтому вы всегда получаете свежие версии ПО.

Security

Why do I have to confirm packages now? Is there a way to remove this?

tl;dr — Yes, completely possible. Use or turn on .

Also check out the help menus now — ,

The one that is the most important right now is the release (in this case 0.9.9), once we reach v1 we will be fully SemVer compliant and breaking changes will constitute a major version bump (we’re still SemVer in a less than v1), so you can scan breaking changes and major new features in an release, new compatible features in a release, and releases will only contain compatible fixes for the current release.

Security Prompt for confirmation: For security reasons, we now stop for confirmation before changing the state of the system on most commands. You can pass -y to confirm any prompts or set a value in the config that will globally confirm and behave like older versions of Chocolatey (allowGlobalConfirmation, see choco feature -h for how to enable).

Some folks may find the change quite annoying. The perspective of some folks isn’t the perspective of everyone and we have some very security-conscious folks that want a verification of what they requested is what they end up with. So this prompt is extremely important for them. We are moving to a more secure by default approach so this change was important to get us there. Security related changes are some of the only things you will see that affect Chocolatey in such a way.

We spent many months stressing over this change because of the breaking part and decided it wasn’t going to get easier to change later. We’ve added the ability for you to set Chocolatey back to the way it was before with and if the prompts annoy you, you should probably look at making this change.

What doesn’t the website implement x security standard?

While we keep up with most security aspects, sometimes we miss things. Always feel free to reach out to us if you feel there is something we should implement to make that better.

Установка приложений с помощью Chocolatey

Рекомендуемый способ

Репозиторий Chocolatey содержит постоянно обновляющуюся базу из более чем 5800 бесплатных и условно-бесплатных приложений.

Устанавливаем модуль Chocolatey. Он имеет свой синтаксис, зато приложения можно будет устанавливать, не только из повершела, но и из командной строки. Это делается всего одной командой:

iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’))

Если ругнётся на:

Невозможно загрузить файл \chocolatey\chocInstall\tools\chocolateyInstall.ps1, так как выполнение сценариев отключено в этой системе.

То измените .

Это всё что нужно сделать. Теперь вы можете устанавливать приложения, используя простейший синтаксис проекта Chocolatey.
Для полноценного управления установкой приложений нам потребуется 5 команд:

  • cinst название_пакета — установка приложения
  • cuninst название_пакета — удаление приложения
  • cup название_пакета — обновление приложения
  • cup all — обновление всех установленных приложений
  • clist название_пакета — поиск приложений

Например, для установки браузера Opera — запустим экземпляр командной строки CMD или PowerShell от имени Администратора. В адресную строку введём название команды cinst, название приложения opera и пару параметров:

cinst opera ––force ‑y

Параметр ‑‑force — будет игнорировать все ошибки, а так-же используется для принудительной переустановки приложения.
Ключ ‑y — будет отвечать на все вопросы скриптов, установщика и системы утвердительно.

Для удаления — набирайте cuninst, название программы и ключ -y, например:

cuninst opera -y

А как же искать приложения? Для примера узнаем какое название имеет в каталоге Chocolatey десктопный Telegram. Для этого пишем команду clist и через пробел предполагаемое название пакета:

clist telegram

Как правило, первая же строчка и будет названием пакета с указанием её текущей версии в каталоге.

По такому же принципу, вы можете обновлять приложения. Команды для обновления сразу всех программ или по отдельности были чуть выше.

Server

Many IT teams still rely on manual configurations, custom scripts, golden images or outdated tools to manage Windows infrastructure. This results in errors and slow deployments, or worse — unpatched environments that leave you susceptible to security incidents.

From a server point of view you need to ensure a consistent, reliable approach without having manual intervention, and allowing you to run the businesses on the software and having to care, water, and feed the servers.
When you get to the world of cloud and containers this is only amplified as you are managing the unknown.

Chocolatey provides a standardized, scalable approach to server management. From setting up a new server, to ensuring critical updates are in place, or supporting a migration project.

Submitting Issues

If you have found an issue with Chocolatey GUI, this is the place to submit.

Observe the following help for submitting an issue:

Prerequisites:

  • The issue has to do with Chocolatey GUI itself and is not a package or website issue.
  • Please check to see if your issue already exists with a quick search of the issues. Start with one relevant term and then add if you get too many results.
  • You are not submitting an Enhancement. Enhancements should observe CONTRIBUTING guidelines.

Submitting a ticket:

  • We’ll need debug and verbose output, so please run and capture the log with or . You can submit that with the issue or create a gist and link it.
  • Please note that the debug/verbose output for some commands may have sensitive data (passwords or apiKeys) related to Chocolatey, so please remove those if they are there prior to submitting the issue.
  • choco.exe logs to a file in . You can grab the specific log output from there so you don’t have to capture or redirect screen output. Please limit the amount included to just the command run (the log is appended to with every command).
  • Please save the log output in a gist (save the file as ) and link to the gist from the issue. Feel free to create it as secret so it doesn’t fill up against your public gists. Anyone with a direct link can still get to secret gists. If you accidentally include secret information in your gist, please delete it and create a new one (gist history can be seen by anyone) and update the link in the ticket (issue history is not retained except by email — deleting the gist ensures that no one can get to it). Using gists this way also keeps accidental secrets from being shared in the ticket in the first place as well.
  • We’ll need the entire log output from the run, so please don’t limit it down to areas you feel are relevant. You may miss some important details we’ll need to know. This will help expedite issue triage.
  • It’s helpful to include the version of choco, the version of the OS, and the version of PowerShell (Posh), but the debug script should capture all of those pieces of information.
  • Include screenshots and/or animated gif’s whenever possible, they help show us exactly what the problem is.

Что в позитиве

Чистый экран входа

«Дверь» в OS X Yosemite стала намного более чистой и стильной, и при первом входе пользователя в систему она приветствует его легкой плавной анимацией.

Экран входа в OS X Yosemite отлично сделан

Новые значки программ

Большинство новых иконок смотрятся четко и аккуратно. В отличие от аляповатых и непонятных значков iOS 7, которые мы наблюдаем с прошлого года, пиктограммы стандартных мак-приложений Apple освежила, но при этом не сделала их кислотно-яркими.

Новые пиктограммы в OS X Yosemite

В частности, хорошо получился новый значок мусорной корзины. Крэйг Федериги отметил, как много времени понадобилось на создание этой иконки, и по результату это видно.

Великолепная иконка мусорного ведра

Contributing

If you would like to contribute code or help squash a bug or two, that’s awesome. Please familiarize yourself with CONTRIBUTING.

Building

  • It is assumed that a version of Visual Studio 2017 is already installed on the machine being used to complete the build
    • Visual Studio 2017 shipped with an MSBuild Tool Version for 2015, if you don’t have 2017 installed, and, for example, only have Visual Studio 2019 installed, then it is likely that the build will fail.
    • In this situation, you have two choices
      • Install the Microsoft Build Tools for 2015. This can be done using the following command
      • Uncomment the line in the recipe.cake file that contains and comment the line above it
  • OPTIONAL: If you have Visual Studio 2017 installed, you may need to set environment variable. You can typically find that at . Run something like (for build machines, use instead of ).
  • From and Administrative PowerShell Window, navigate to the folder where you have cloned the Chocolatey GUI repository and run , this will run Cake and it will go through the build script.

Модуль PackageManagement

Модуль PackageManagement уже встроен в Windows 10, а для его работы требуется PowerShell 5. Поэтому для работы менеджера пакетов в Windows 8.1 нужно сначала  установить Windows Management Framework 5.0. Также Microsoft выпустила отдельный модуль для работы менеджера пакетов и на PowerShell версий 3 и 4.

Выведем список доступных командлетов PowerShell в модуле PackageManagement:

В текущей версии модуля (v 1.0.0.1) имеются такие команды:

  • Find-Package — поиск пакета (программы) в доступных репозиториях
  • Get-Package — получить список установленных пакетов
  • Get-PackageProvider — список провайдеров (поставщиков пакетов), доступных на компьютере
  • Get-PackageSource — список доступных источников пакетов
  • Install-Package — установить пакет (программу) на компьютере
  • Register-PackageSource — добавить источник пакетов для провайдера
  • Save-Package — сохранить пакет локально без его установки
  • Set-PackageSource — задать провайдер в качестве источника пакетов
  • Uninstall-Package — удалить программу (пакет)
  • Unregister-PackageSource — удалить поставщика из списка источников пакетов

Using Chocolatey

  1. Open a command line.
  2. Type and press Enter.
  3. If you have UAC turned on or are not an administrator, Chocolatey is going to request administrative permission at some point (at least once during the process). Otherwise it will not be able to finish what it is doing successfully. If you don’t have UAC turned on, it will just continue on without stopping to bother you.
  4. That’s it. Pretty simple but powerful little concept!

Overriding default install directory or other advanced install concepts

  1. If you wanted to pass native argument to the installer, like the install directory, you would need to know the silent argument passed to that particular installer and then you would specify it on the command line or in the packages.config.

What Are Chocolatey Packages?

Chocolatey packages are known as nupkg files, which is a compiled NuSpec or a fancy zip file that knows about package metadata (including dependencies and versioning). These packages are an enhanced NuGet package, they have additional metadata that is specific to Chocolatey. Chocolatey is also compatible with vanilla NuGet packages. A Chocolatey package can contain embedded software and/or automation scripts.

The closer the underlying software a package represents is to the package (as in executables and files included in the package), the more Chocolatey behaves like a package manager.

Integrations

Most organizations have already invested in tools and solutions across their IT environment. Before adding more tools, IT teams may need to ensure that their existing investments are maximized.
Teams also need to ensure they don’t get locked in proprietary technologies that don’t integrate well in their environments.

Chocolatey maximizes existing knowledge by bringing PowerShell to the forefront and allowing you to leverage existing tools you are already using. Chocolatey has integrations and is used in conjunction with leading and emerging technologies:

  • Configuration Management tools like Puppet, Chef, Ansible, and Powershell DSC
  • Repository solutions such as JFrog Artifactory, Sonatype Nexus, and Inedo ProGet
  • Continuous Integration Servers such as Jenkins, Circle CI, AppVeyor, and TeamCity
  • Source Control providers like GitHub and GitLab
  • Microsoft tools like SCCM and Intune and third party endpoint management solutions like Connectwise Automate, Ivanti, and Altiris

Chocolatey’s unique ability to work with any Windows machine, anywhere, allows you to deploy packages easily and efficiently in every environment, from on-premises, to the cloud (Azure, AWS, etc), to Docker containers, through many different tools and technologies.

Check back later for detailed integration use cases!

Преимущества данного способа установки программ

y http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>le=»text-align: justify;»>Подводя итог, еще раз отмечу преимущества использования менеджера пакетов Chocolatey для установки программ (для начинающего пользователя):

  1. Вы получаете официальные программы из надежных источников и не рискуете, пытаясь найти то же ПО в Интернете.
  2. При установке программы не требуется следить за тем, чтобы не установилось чего-либо ненужного, будет установлено чистое приложение.
  3. Это действительно быстрее, чем поиск официального сайта и страницы загрузки на нем вручную.
  4. Вы можете создать файл сценария (.bat, .ps1) или просто установить сразу все нужные бесплатные программы одной командой (например, после переустановки Windows), то есть для установки двух десятков программ, включая антивирусы, утилиты и проигрыватели, вам нужно лишь один раз ввести команду, после чего даже не понадобиться нажимать кнопку «Далее».

Надеюсь, кому-то из моих читателей эта информация будет полезной.

А вдруг и это будет интересно:

Установка программ с помощью Chocolatey

Основной особенностью данного менеджера пакетов, является возможность установки программного обеспечения Windows с помощью одной команды. Вместо того, чтобы посещать веб-сайт и вручную выбирать установщик, вы можете запустить PowerShell и ввести что-то вроде следующего:

choco install vlc

Это позволит загрузить и установить VLC Media Player в вашу систему, не требуя никаких дополнительных действий с вашей стороны. Вы увидите информацию о прогрессе, отображаемую на вашей консоли, когда VLC будет добавлен в вашу систему. Затем вы найдете его в меню «Пуск», как если бы вы запускали установщик самостоятельно.

Примечание: Некоторые программы могут попросить вас запустить скрипт во время их установки. При запросе введите «A» для «All» в консоли и нажмите клавишу Enter, чтобы подтвердить это приглашение и завершить установку.

Без лишней скромности — Chocolatey поддерживает тысячи разных программ, точнее 6869 пакетов, поддерживаемых сообществом. Вы можете посмотреть их, в хранилище пакетов Chocolatey. Некоторые из самых популярных вариантов включают Chrome, Adobe Reader, Firefox, WinRAR и Skype. В хранилище пакетов отображается имя, которое нужно добавить к команде «choco install» для установки любой программы.

Обновление установленных программ

Менеджер пакетов упрощает обновление установленных программ. Выполните следующую команду, чтобы обновить все программы в вашей системе, установленные с помощью Chocolatey:

choco upgrade all

Вы также можете передать имя для обновления одной программы:

choco ugprade vlc

Chocolatey проверит, требуются ли обновления, и автоматически установит новую версию. Если вы хотите узнать, доступны ли обновления, не устанавливая их, вместо этого запустите

choco outdated

Еще команды

Есть несколько других команд, которые вы, вероятно, найдете полезными.

При вводе команды «choco list -lo» будет показан список всех установленных вами программ.

Вы также можете использовать поиск:

 choco search 

Замените запрос , чтобы искать в хранилище пакетов и отобразить все доступные программы, так что вам даже не понадобится веб-браузер для поиска нового программного обеспечения.

Например, будем искать торрент клиент:

choco search torrent

Получаем вывод, выберем, например transmission. Да, да, популярный торрент клиент, ранее доступный только для Mac OS X и Linux дистрибутивов — Transmission официально выпущен  для Windows 10.

Получив таким образом имя, устанавливаем его командой:

choco install transmission

Несколько секунд и программа установлена, запустите ее с помощью ярлыка на рабочем столе или найдите ее в меню «Пуск».

Когда дело доходит до удаления программы, используйте команду «choco uninstall», добавляя имя программы. Менеджер отслеживает удаление приложений другими способами — если вы устанавливаете программу с Chocolatey, но затем удаляете ее из приложения «Параметры Windows» или Панели управления, она также автоматически исчезает из менеджера пакетов.

Мы рассмотрели в этой статье, самые простые возможности. Для опытных пользователей существует множество параметров конфигурации, а также возможность запуска локальных прокси-серверов, кэшей и репозиториев пакетов.

Графический Интерфейс

Наконец, стоит отметить, что Chocolatey имеет дополнительный графический интерфейс, который помогает вам взаимодействовать с вашими пакетами и устанавливать новые. Как и следовало ожидать, установка пользовательского интерфейса осуществляется через саму Chocolatey!

Запустите «choco install chocolateygui», чтобы установить графический интерфейс.

choco install chocolateygui

После этого вы сможете запустить графический интерфейс из меню «Пуск» с помощью ярлыка «Chocolatey GUI».

Это дает вам простой графический интерфейс для просмотра установленных пакетов, проверки обновлений и настройки параметров Chocolatey. Вы можете просмотреть каталог программ, нажав «Chocolatey» на левой боковой панели. Здесь вы можете искать новые программы и устанавливать их одним кликом мыши, избегая дальнейшего использования PowerShell.

Поделись этим.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделитесь с друзьями:
Технарь
Добавить комментарий

Нажимая на кнопку "Отправить комментарий", я даю согласие на обработку персональных данных и принимаю политику конфиденциальности.