How to install chocolatey package manager on windows 10/8/7

Централизованное управление кластером 1С Предприятия, состоящим из нескольких рабочих серверов, работающих на платформе GNU/Linux

При эксплуатации крупных информационных систем, в состав которых могут входить десятки серверов 1С Предприятия, зачастую возникают ситуации, требующие однотипных действий на всех серверах кластера 1С Предприятия или на всех серверах контура. В настоящей статье представлен способ централизованного управления серверами 1С Предприятия, работающими на платформе GNU/Linux. Подобный подход может быть использован и для других задач, возникающих в процессе эксплуатации крупных систем, с целью сокращения как временных затрат специалистов, так и времени простоя системы.

1 стартмани

Обзор компонентов

Диспетчеры пакетов, такие как apt-get, хорошо известны среди разработчиков Linux и гораздо меньше — среди тех, кто работает с Windows.
К таким диспетчерам пакетов относится Chocolatey, общие сведения о котором изложены в записи блога Скотта Хансельмана (Scott Hanselman). В двух словах, Chocolatey позволяет с помощью командной строки устанавливать пакеты из центрального репозитория в Windows. Вы можете создать собственный репозиторий и управлять им, а Chocolatey будет устанавливать пакеты из любого указанного вами количества репозиториев.

PowerShell DSC — это средство PowerShell, которое позволяет объявить конфигурацию, необходимую для компьютера. Например, если требуется установить Chocolatey, установить службы IIS, открыть порт 80 и установить версию 1.0.0 веб-сайта, Configuration Manager DSC (LCM) реализует эту конфигурацию. Опрашиваемый сервер DSC содержит хранилище конфигураций для компьютеров. Локальный диспетчер конфигураций на каждом компьютере периодически проверяет, совпадает ли его конфигурация с сохраненной конфигурацией. Он либо сообщает о состоянии, либо пытается привести компьютер в соответствие с сохраненной конфигурацией. Сохраненную конфигурацию на опрашивающем сервере можно изменить, чтобы привести компьютер или набор компьютеров в соответствие с измененной конфигурацией.

Ресурс DSC — это модуль кода, который имеет определенные возможности, такие как управление сетевыми подключениями, Active Directory или SQL Server. Ресурс DSC Chocolatey может получать доступ к серверу NuGet, загружать и устанавливать пакеты и т. д. Имеется также множество других ресурсов DSC, доступных в коллекции PowerShell. Эти модули устанавливаются на опрашиваемом сервере State Configuration службы автоматизации Azure, поэтому их можно использовать в ваших конфигурациях.

Одна из ключевых особенностей шаблона Resource Manager заключается в возможности установить на виртуальной машине расширение виртуальной машины во время подготовки. Расширение VM предоставляет определенные возможности, такие как выполнение пользовательского сценария, установка антивирусного программного обеспечения и выполнение сценария конфигурации DSC. Существует много других типов расширений VM.

How To Pass Options / Switches

You can pass options and switches in the following ways:

  • Unless stated otherwise, an option/switch should only be passed one
    time. Otherwise you may find weird/non-supported behavior.
  • , , or (one character switches should not use )
  • Option Bundling / Bundled Options: One character switches can be
    bundled. e.g. (debug), (force), (verbose), and
    (confirm yes) can be bundled as .
  • Use Equals: You can also include or not include an equals sign
    between options and values.
  • Quote Values: When you need to quote an entire argument, such as
    when using spaces, please use a combination of double quotes and
    apostrophes (). In cmd.exe you can just use double quotes
    () but in powershell.exe you should use backticks
    () or apostrophes (). Using the combination
    allows for both shells to work without issue, except for when the next
    section applies.
  • Pass quotes in arguments: When you need to pass quoted values to
    to something like a native installer, you are in for a world of fun. In
    cmd.exe you must pass it like this: . In
    PowerShell.exe, you must pass it like this: .
    No other combination will work. In PowerShell.exe if you are on version
    v3+, you can try before to just pass the args through as is,
    which means it should not require any special workarounds.
  • Periods in PowerShell: If you need to pass a period as part of a
    value or a path, PowerShell doesn’t always handle it well. Please
    quote those values using «Quote Values» section above.
  • Options and switches apply to all items passed, so if you are
    installing multiple packages, and you use , choco
    is going to look for and try to install version 1.0.0 of every
    package passed. So please split out multiple package calls when
    wanting to pass specific options.

Deploying Branding

What follows is a suggestion on how a branded version of Chocolatey GUI can be
deployed out to your environment.

  1. Follow the steps above to place the branding image assets into the correct location.

  2. Run the Chocolatey GUI application to generate the ChocolateyGuiBranding.dll

  3. Create a new folder on your file system to house the branding Chocolatey Package

  4. In this folder, create a folder

  5. Copy the generated into this folder

  6. Copy the following xml into a file called .

  7. Copy the following PowerShell into a file called

  8. Copy the following PowerShell into a file called

  9. Copy the following PowerShell into a file called

  10. Run the command

  11. Deploy the generated to the repository that you are using

  12. Install the Chocolatey GUI Branding package

Scripting / Integration — Best Practices / Style Guide

When writing scripts, such as PowerShell scripts passing options and
switches, there are some best practices to follow to ensure that you
don’t run into issues later. This also applies to integrations that
are calling Chocolatey and parsing output. Chocolatey uses
PowerShell, but it is an exe, so it cannot return PowerShell objects.

Following these practices ensures both readability of your scripts AND
compatibility across different versions and editions of Chocolatey.
Following this guide will ensure your experience is not frustrating
based on choco not receiving things you think you are passing to it.

  • For consistency, always use , not . Never use
    shortcut commands like or .
  • Always have the command as the first argument to . e.g.
    , where is the command.
  • If there is a subcommand, ensure that is the second argument. e.g.
    , where is the command and is the
    subcommand.
  • Typically the subject comes next. If installing packages, the
    subject would be the package names, e.g. .
  • Never use ‘nupkg’ or point directly to a nupkg file UNLESS using
    ‘choco push’. Use the source folder instead, e.g. instead of
    or .
  • Switches and parameters are called simply options. Options come
    after the subject. e.g. .
  • Never use the force option (/) in scripts (or really
    otherwise as a default mode of use). Force is an override on
    Chocolatey behavior. If you are wondering why Chocolatey isn’t doing
    something like the documentation says it should, it’s likely because
    you are using force. Stop.
  • Always use full option name. If the short option is , and the
    full option is , use . The only acceptable short
    option for use in scripts is . Find option names in help docs
    online or through /.
  • For scripts that are running automated, always use . Do note
    that even with passed, some things / state issues detected will
    temporarily stop for input — the key here is temporarily. They will
    continue without requiring any action after the temporary timeout
    (typically 30 seconds).
  • Full option names are prepended with two dashes, e.g. or
    .
  • When setting a value to an option, always put an equals ()
    between the name and the setting, e.g. .
  • When setting a value to an option, always surround the value
    properly with double quotes bookending apostrophes, e.g.
    .
  • If you are building PowerShell scripts, you can most likely just
    simply use apostrophes surrounding option values, e.g.
    .
  • Prefer upgrade to install in scripts. You can’t to a newer
    version of something, but you can which will do both
    upgrade or install (unless switched off explicitly).
  • If you are sharing the script with others, pass to be
    explicit about where the package is coming from. Use full link and
    not source name (‘https://community.chocolatey.org/api/v2’ versus
    ‘chocolatey’).
  • If parsing output, you might want to use / to
    get output in a more machine parseable format. > NOTE Not all
    commands handle return of information in an easily digestible
    output.
  • Use exit codes to determine status. Chocolatey exits with 0 when
    everything worked appropriately and other exits codes like 1 when
    things error. There are package specific exit codes that are
    recommended to be used and reboot indicating exit codes as well. To
    check exit code when using PowerShell, immediately call
    to get the value choco exited with.

Here’s an example following bad practices (line breaks added for
readability):

Now here is that example written with best practices (again line
breaks added for readability — there are not line continuations
for choco):

Note the differences between the two:

  • Which is more self-documenting?
  • Which will allow for the newest version of something installed or
    upgraded to (which allows for more environmental consistency on
    packages and versions)?
  • Which may throw an error on a badly passed option?
  • Which will throw errors on unknown option values? See explanation
    below.

Chocolatey ignores options it doesn’t understand, but it can only
ignore option values if they are tied to the option with an
equals sign (‘=’). Note those last two options in the examples above?
If you roll off of a commercial edition or someone with older version
attempts to run the badly crafted script , they are likely to see errors on
‘Yaass’ and ‘dude upgrade’ because they are not explicitly tied to the
option they are written after. Now compare that to the other script.
Choco will ignore and
as a whole when it doesn’t
register the options. This means that your script doesn’t error.

Following these scripting best practices will ensure your scripts work
everywhere they are used and with newer versions of Chocolatey.

Child Pages

Config

Config Command (choco config)

Download

Download Command (choco download)

Export

Export Command (choco export)

Find

Find Command (choco search)

Feature

Feature Command (choco feature)

Help

Help Command (choco help)

Info

Info Command (choco info)

Install

Install Command (choco install)

List/Search

List/Search Command (choco list)

Optimize

Optimize Command (choco optimize)

Outdated

Outdated Command (choco outdated)

Pin

Pin Command (choco pin)

Search

Search Command (choco search)

SetApiKey

SetApiKey Command (choco setapikey)

Source

Source Command (choco source)

Sources

Sources Command (choco sources)

Support

Support Command (choco support)

Sync

Sync Command (choco sync)

Synchronize

Synchronize Command (choco synchronize)

Uninstall

Uninstall Command (choco uninstall)

UnpackSelf

UnpackSelf Command (choco unpackself)

Update

Update Command (choco update)

Upgrade

Upgrade Command (choco upgrade)

Version

Version Command (choco version)

Chocolatey Installation

The request was aborted: Could not create SSL/TLS secure channel

If you see the following: Exception calling «DownloadString» with «1» argument(s): «The request was aborted: Could not create SSL/TLS secure channel.» then you are likely running an older machine that needs to be upgraded to be able to use TLS 1.2 at a minimum.

Chocolatey.org now requires TLS 1.2 at a minimum. Please see https://chocolatey.org/blog/remove-support-for-old-tls-versions. The post provides options if you have older clients that need to install Chocolatey.

The underlying connection was closed

If you see an error that looks similar to the following:

Chocolatey.org now requires TLS 1.2 at a minimum. Please see https://chocolatey.org/blog/remove-support-for-old-tls-versions. The post provides options if you have older clients that need to install Chocolatey.

Naming your package

The title of your package ( tag in the nuspec) should be the same as the name of the application. Follow the official spelling, use upper and lower case and don’t forget the spaces. Examples of correct package titles are: Google Chrome, CCleaner, PuTTY and FileZilla. The title will appear on the left side in the package list of the Chocolatey gallery, followed by the version.

There are some guidelines in terms of the package id ( tag in the nuspec):

  • Use only lowercase letters, even if you used uppercase letters in the package title. (This is considered a guideline because it is correctable in other ways). Once a package is submitted (even prior moderation), the Gallery will always show the id with the casing of the first package version. In addition, changing the casing of the package id may have negative side effects on dependencies (note: this last statement needs verified).
  • If the original application name consists of compound words without spaces (CamelCase), just as MKVToolNix, TightVNC and VirtualBox, the package id’s are simply the same (but lowercase of course): , , and .
  • If the name of the application contains multiple words separated by spaces, such as MusicBrainz Picard or Adobe Reader, replace the spaces with the hyphen-minus character “-” (U+002D) or just omit them. Don’t use dots. They should be used only if the original application name contains dots (e. g. Paint.NET). Hence the correct id’s of the previously mentioned applications can be or . It is highly suggested to use the hyphen method when there are long package names, because that increases readability.
  • For sub-packages, use the hyphen-minus character “-” (U+002D) as separator, not a dot. Sub-packages are intended for separate packages that include extensions, modules or additional features/files for other applications. Therefore is a proper package id, because it adds the language files for the main application which in this case is KeePass. Another example is for the help pack for LibreOffice, the open source office suite.
  • If you want to package an open source application, look on the repositories of some popular Linux distributions, such as , Ubuntu and Arch Linux if they already have a package of it. If that is the case, use the same package id. This will make it easier for Linux and Windows users, because then they don’t have to remember and use different package names.

These guidelines are already commonly applied on packages for all major Linux distributions, because they lead to a more consistent look of software repositories, easier to remember package id’s and less considerations about the naming for package creators.

Note that a lot of packages in the Chocolatey Gallery don’t follow these guidelines. The simple reason is that the affected packages were created before the introduction of these guidelines.

If you are going to offer a package that has both an installer and an archive (zip or executable only) version of the application, create three packages  — see and

Установка программ с помощью 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.

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

How does Chocolatey work?

How the heck does this all work?

Installation

  1. Chocolatey uses NuGet (NuGet.Core.dll) to retrieve the package from the source. This is typically a nupkg that is stored in a folder, share, or an OData location (HTTP/HTTPS). For more information on sources, please see Sources and Source Repositories.
  2. The package is installed into . The package install location is not configurable — the package must install here for tracking, upgrade, and uninstall purposes. The software that may be installed later during this process is configurable. See to understand the difference between «package» and «software» as the terms relate to Chocolatey.
  3. Choco determines if it is self-contained or has automation scripts — PowerShell scripts (*.ps1 files) and possibly other formats at a later date.
  4. Choco takes a registry snapshot for later comparison.
  5. 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).
  6. Choco compares the snapshot and determines uninstaller information and saves that to a .registry file.
  7. Choco snapshots the folder based on all files that are currently in the package directory.
  8. 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.

When a package has an exe file, Chocolatey will create a link «shortcut» to the file (called a shim) so that you can run that tool anywhere on the machine. See shimming for more information.
When a package has a chocolateyInstall.ps1, it will run the script. The instructions in the file can be anything. This is limited only by the .NET framework and PowerShell.
Most of the Chocolatey packages that take advantage of the PowerShell download an application installer and execute it silently.

Why not use an existing Windows package manager?

Believe me, I wanted there to be something existing on Windows that would fit the bill. Package management is not a glorious job. Especially on Windows. It’s taking all of the different native installers, archives, and straight executable downloads and making a simple interface for consumers to issue the same install command for all of them. Here are/were my needs:

  • Good CLI that is simple to use.
  • Main repository that takes packages contributions from the community (and is being maintained).
  • Ability to use additional/multiple sources.
  • Meta packages that can chain dependencies.
  • Virtual packages.
  • Packages should be easy to create / maintain.
  • Packages should be concise and be able to be created without worrying about distribution rights.
  • Unattended installs
  • Installation of multiple packages with one command.

To date, Chocolatey does all of this (virtual packages is coming).

What is the purpose of Chocolatey?

How many times do you hear about an awesome tool/application from your friends and want to try it out? How much effort do you go through to set a tool and all of its requirements up on your machine? Do you realize that all of this manual effort is a pain? It’s a pain we are used to! It’s something we just do and don’t realize we are wasting time doing all of this manual process. And worse, when we install applications it’s always… Next Next Next Finish.

There is a better way! Once you start to use Chocolatey to silently install applications, tools, and to quickly set up things on your machine, you will start to realize that it is more of a global automation tool. That makes it an enabler, enabling you to do just about anything. And to repeat it anywhere in the world with little more than an internet connection.

Because Chocolatey is built on top of the NuGet infrastructure, that means you can install packages from Chocolatey.org, NuGet.org, MyGet.org, file shares, directories, custom feeds and from private feeds. That means you can set up your own server (even private) and your own internal packages with more company specific packages.

Сведения о примере использования

В начале примера в этой статье создается виртуальная машина с помощью универсального образа Windows Server 2012 R2 из коллекции Azure. Ее можно запустить из любого сохраненного образа, а затем настроить, используя конфигурацию DSC.
Однако изменение конфигурации, встроенной в образ, требует гораздо больше усилий, чем динамическое обновление конфигурации с помощью DSC.

Для использования этого метода на виртуальных машинах не обязательно использовать шаблон Resource Manager и расширение VM. Кроме того, виртуальные машины, на которых должно выполняться непрерывное развертывание, не обязательно должны размещаться в Azure. На виртуальной машине достаточно установить Chocolatey и настроить локальный диспетчер конфигураций, чтобы указать для нее расположение опрашивающего сервера.

На время обновления пакета на виртуальной машине в рабочей среде эту виртуальную машину придется вывести из эксплуатации. Это можно сделать разными способами. Например, на виртуальной машине, которая находится под контролем балансировщика нагрузки Azure, можно добавить настраиваемый зонд. При обновлении виртуальной машины конечная точка зонда должна возвращать значение 400. Настройка, необходимая для этого изменения, может содержаться в вашей конфигурации, и после завершения обновления вы сможете снова переключиться на возвращение значения 200.

Полный исходный код для этого примера хранится в этом проекте Visual Studio на сайте GitHub.

But what about security?

Chocolatey is convenient, but there’s no way around the fact it’s not an ideal choice if you’re concerned about security for your PC right now. Installing programs with Chocolatey requires that you trust the package creator.

You could monitor Chocolatey as it installs your programs to see which sites the downloads are coming from, but that defeats the convenience of using Chocolatey as an automated process.

The implicit trust model probably means that pulling from the Chocolatey community feed wouldn’t be the best choice for large enterprises or even smaller companies. That said, Chocolatey can be tuned to rely on a private feed controlled by the company where all packages are vetted by the IT department.

While security is not ideal right now, Reynolds says there are some big changes in the works for future versions of Chocolatey. Over the next year, trusted community members will begin moderating the stable feed and all packages will be reviewed before being added. Approved packages will include cryptographic signing by the moderator who approved it.  

Future versions of Chocolatey will include a scanning algorithm to detect packages with malicious intent. Users will also be able to control who they trust by accepting or denying packages based on public key signatures, just like package managers in Linux. 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector