Faqs
Содержание:
Deploying Branding
What follows is a suggestion on how a branded version of Chocolatey GUI can be
deployed out to your environment.
-
Follow the steps above to place the branding image assets into the correct location.
-
Run the Chocolatey GUI application to generate the ChocolateyGuiBranding.dll
-
Create a new folder on your file system to house the branding Chocolatey Package
-
In this folder, create a folder
-
Copy the generated into this folder
-
Copy the following xml into a file called .
-
Copy the following PowerShell into a file called
-
Copy the following PowerShell into a file called
-
Copy the following PowerShell into a file called
-
Run the command
-
Deploy the generated to the repository that you are using
-
Install the Chocolatey GUI Branding package
Character encoding
- Use the UTF-8 character encoding for the and files. If you don’t respect this rule, some characters are not displayed correctly in the Gallery on Chocolatey.org, because the Gallery assumes .
- Byte Order Mark (BOM) is optional for .. A is not required but it won’t hurt anything if it is found.
- PowerShell scripts need to be saved in UTF-8 with . PowerShell is ignoring the standards and needs a in order to recognize scripts as . Otherwise it processes non characters incorrectly.
- Don’t use the default Windows Editor. While newer versions of Notepad have improved its ability to handle line endings and UTF-8 w/out BOM, it is still behind in capabilities as compared to other editors. Alternatives:
- Visual Studio Code
- Notepad++
- Geany
- Use this XML declaration: .
How does Chocolatey work?
How the heck does this all work?
Installation
- 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.
- 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.
- Choco determines if it is self-contained or has automation scripts — PowerShell scripts (*.ps1 files) and possibly other formats at a later date.
- Choco takes a registry snapshot for later comparison.
- 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).
- Choco compares the snapshot and determines uninstaller information and saves that to a .registry file.
- Choco snapshots the folder based on all files that are currently in the package directory.
- 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
- 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.
- Similar to install, except choco will make a backup of the package folder (and only the package folder) prior to attempting upgrade.
- 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.
- 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
- Choco makes the determination that the package is actually installed.
- 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.
- Choco will make a backup of the package folder.
- The automation script is run if found. This should be used to clean up anything that is put there with the install script.
- 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.
- 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.
- 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.
Parameters
-PackageName <String>
The name of the package — while this is an arbitrary value, it’s
recommended that it matches the package id.
| Property | Value |
|---|---|
| Aliases | |
| Required? | true |
| Position? | 1 |
| Default Value | |
| Accept Pipeline Input? | false |
-FileType
This is the extension of the file. This should be either exe or msi.
If what is provided is empty or null, Chocolatey will use ‘exe’
starting in 0.10.1.
| Property | Value |
|---|---|
| Aliases | installerType |
| Required? | false |
| Position? | 2 |
| Default Value | exe |
| Accept Pipeline Input? | false |
-SilentArgs >]
OPTIONAL — These are the parameters to pass to the native uninstaller,
including any arguments to make the uninstaller silent/unattended.
Licensed editions of Chocolatey will automatically determine the
installer type and merge the arguments with what is provided here.
Try any of the to get the silent (unattended) uninstaller —
. With msi it is always
. Please pass it in still but it will be overridden by
Chocolatey to . If you don’t pass anything it could invoke the
installer with out any arguments. That means a nonsilent installer.
Please include the tag in your Chocolatey package if you
are not setting up a silent/unattended package. Please note that if you
are submitting to the community repository, it is nearly a requirement
for the package to be completely unattended.
| Property | Value |
|---|---|
| Aliases | |
| Required? | false |
| Position? | 3 |
| Default Value | |
| Accept Pipeline Input? | false |
-File
The full path to the native uninstaller to run.
| Property | Value |
|---|---|
| Aliases | |
| Required? | false |
| Position? | 4 |
| Default Value | |
| Accept Pipeline Input? | false |
-ValidExitCodes
Array of exit codes indicating success. Defaults to .
| Property | Value |
|---|---|
| Aliases | |
| Required? | false |
| Position? | named |
| Default Value | @(0) |
| Accept Pipeline Input? | false |
-IgnoredArguments >]
Allows splatting with arguments that do not apply. Do not use directly.
| Property | Value |
|---|---|
| Aliases | |
| Required? | false |
| Position? | named |
| Default Value | |
| Accept Pipeline Input? | false |
<CommonParameters>
This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see http://go.microsoft.com/fwlink/p/?LinkID=113216 .
Шаг 3. Добавление требуемых ресурсов DSC на опрашиваемый сервер
Коллекция PowerShell содержит средства для установки ресурсов DSC в учетной записи службы автоматизации Azure.
Перейдите к нужному ресурсу и нажмите кнопку «Развернуть в службе автоматизации Azure».

Недавно на портал Azure добавлена возможность получать новые модули и обновлять имеющиеся. Щелкните ресурс учетной записи службы автоматизации, плитку «Ресурсы» и, наконец, плитку «Модули». Значок «Обзор коллекции» позволяет просмотреть список модулей в коллекции, перейти к подробным сведениям и в конечном итоге импортировать модуль в учетную запись службы автоматизации. Это отличный способ периодически обновлять модули. Кроме того, во время импорта проверяется наличие зависимостей от других модулей, чтобы обеспечить полную синхронизацию.
Существует также ручной подход, используемый только один раз для каждого ресурса, если потом вы не будете его обновлять. Дополнительные сведения о разработке модулей интеграции PowerShell см. в статье Разработка модулей интеграции для службы автоматизации Azure.
Примечание
Структура папок модуля интеграции PowerShell для компьютеров Windows немного отличается от структуры папок, ожидаемой службой автоматизации Azure.
-
Установите Windows Management Framework 5 (не требуется для Windows 10).
-
Установка модуля интеграции.
-
Скопируйте папку модуля из расположения c:\Program Files\WindowsPowerShell\Modules\MODULE-NAME во временную папку.
-
Удалите примеры и документацию из основной папки.
-
Упакуйте основную папку, присвоив ZIP-файлу такое же имя, как у папки.
-
Поместите ZIP-файл в легкодоступное расположение HTTP, например хранилище BLOB-объектов в учетной записи службы хранилища Azure.
-
Выполните следующую команду.
Приведенный здесь пример выполняет эти действия для cChoco и xNetworking.
Perhaps the easiest to set up and recommended for testing quick and dirty scenarios, local folder is easily a strong point when you need a quick source for packages.
Advantages
- Speed of setup (can be setup almost immediately).
- Package store is filesystem.
- Can be easily upgrade to Simple Server.
- Permissions are based on file system/share permissions.
- Can manage PowerShell gallery type packages.
- There is no limitation on package sizes (or rather, it can likely handle 100MB+ file sizes, maybe even GB sized packages). Don’t create multiple GB sized packages, what is wrong with you?!
Disadvantages
- Anyone with permission can push and overwrite packages.
- No HTTP/HTTPS pushing. Must be able to access the folder/share to push to it.
- Starts to affect choco performance once the source has over 500 packages (maybe?).
- No tracking on number of downloads / no package statistics
- Big disadvantage: For a file share there is not a guarantee of package version immutability. Does not do anything to keep from package versions being overwritten. This provides no immutability of a package version and no guarantee that a version of a package installed is the same as the version in the source.
No really, it’s that easy. Just set your permissions appropriately and put packages in the folder (no subfolders). You are already done. Okay, two additional considerations:
The structure should just be a flat folder or share (no subfolders) with nupkgs inside that folder. You get that when you choco push to that location. No subfolders, no type of setup will work for Chocolatey with those local folders and shares.
Local Folder Permissions
Permissions can be interesting with a file share. If you are using machine accounts like LocalSystem, they may not have access to network resources. However there is a way to handle that in domain environments. You would need to grant access to machines or anonymous access to the share (Everyone Read is likely not enough).
A great read on your options can be found at the following Stack Exchange links:
- https://serverfault.com/q/135867/79259
- https://serverfault.com/q/41130/79259
A way to do this with LocalSystem:
- Create a global group on the Domain
- Add this group to the share permissions with «Read» Access
- Add this group to the NTFS permissions with «Read» Access
Okay, how do I create packages?
There are three main elements to a Chocolatey package. Only the nuspec is required (#1 below).
- chocolateyInstall.ps1 — check out the helper reference
- any application files to include (it is highly suggested that you are the author in this case or you have the right to distribute files). EXE files in the package/downloaded to package folder from chocolateyInstall.ps1 will get a link to the command line.
- chocolateyUninstall.ps1, for uninstalling your package. See helper reference for functions available in your script.
There is a video showing the creation of a package: https://www.youtube.com/watch?v=Wt_unjS_SUo
The video is a bit outdated in showing the contents of the chocolateyInstall.ps1. Have a look at what the chocolateyInstall.ps1 looks like now:
Using Chocolatey
Now that you have Chocolatey on your machine (need to install?), you can run several commands.
Take a look at the command reference. We are going to be using the install command.
Let’s install Notepad++.
- Open a command line as an administrator.
- Type and press Enter.
- That’s it. Pretty simple but powerful little concept!
Overriding default install directory or other advanced install concepts
- Yes we support that through the use of install arguments — see
- 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.
- If it was an MSI, then usually you could pass (for cmd.exe, it’s different for PowerShell). See for specifics on passing quoted values through.
- For example, Notepad++ uses the NSIS (NullSoft Scriptable Install System) installer. If we look at the silent options, we see that is how we influence the install directory. So we would pass -note that we are looking at the specific package over the virtual (although you can do the same with notepadplusplus as well).
Is there a better way? Absolutely, see ubiquitous install directory switch!
Обзор компонентов
Диспетчеры пакетов, такие как 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.
Internationalization and localization of packages
For Chocolatey, internationalization and localization of packages is very important, because it has users from all over the world. Many applications support multiple languages, but they use several different methods to achieve that. Therefore, there is no standard how internationalization/localization has to be integrated into packages. However, here are a few examples of packages that use various techniques. You can use them as inspiration for new packages:
- The ideal situation is when an application determines the user’s system language and automatically installs with that language. Then you don’t have to take any action relating to localization, because the application already handles that. Examples of such applications are VLC Media Player and LibreOffice.
- When an application provides different installers for different languages, you should determine the system language and download the appropriate installer. The package for Mozilla Firefox (source code) uses this method.
- Sometimes an application installer or executable has already integrated all supported languages, but doesn’t automatically select the system language during a silent install. Often you can pass an additional install parameter to select the desired language. This is used for example in the CCleaner package (source code).
- Some application use separate language files which must be downloaded separately and put somewhere in the application directory. It is best when you create a separate package for the language files. If your package id is , then call it . The language files package for KeePass is an example how this can be achieved.
FAQ
How do I take advantage of this feature?
This works with all versions of Chocolatey. Just use packages and when those packages have exe files, those are automatically shimmed so they are on the PATH.
How does it work?
Chocolatey uses a tool called ShimGen that inspects an executable and creates a small binary, known as a «shim», that simply calls the executable. Then it places that shim in the . It creates the shim by generating it at runtime based on the actual binary’s information.
How is this better than symlinks?
When you symlink a file on Windows, you must symlink all of its dependencies like dlls and config files. If you put that all into the folder to take advantage of being on the PATH, you can quickly see that you will get into a form of «DLL hell» when other executables depend on different versions of the same DLL. You would also need to symlink folders and files for things like plugins, extensions, skins, and other things that are in the original directory. If you are trying to create a symlink to not add more locations to your PATH environment variable, then this particular shortcoming defeats that purpose entirely.
Shimming by design does not run into this issue.
Does it require admin rights?
No, and this is another thing that sets it apart from symlinks. To create symlinks on Windows, you need to have , which is one of the privileges granted to Administrators.
Why not simple batch redirection?
We tried using batch («.bat») files, and it mostly works, but when applications calling other applications expect the file name to be «.exe», a file named «.bat» doesn’t work. Batch files also don’t work in all shells, and shims do.
Have you thought about shimming in more places?
Yes, but we have not decided whether shimming Program Files is a good idea yet or not. Packages can explicitly enforce shims with Install-BinFile.
I need to shim a non-exe file.
If you are creating a package and you need to shim a file that doesn’t end in .exe (like a .bat file), you should look at Install-BinFile.
I need to exclude a file from shimming.
If you are creating a package and you want to skip creation of a shim for a particular file, you can create a «*.ignore» file.
Set an empty file next to the executable (or where it will be downloaded/unpacked to), sharing the same name with the executable and appending «.ignore». For example, if your file is named «», you need a file named «» (pay attention to case — «» may not work with all versions of Chocolatey).
I have architecture specific binaries to shim
If you are creating a package where you have two binaries (or sets of binaries) to shim depending on architecture, one for x86 and one for x64, you can put them in sub-folders and the correct one(s) will be shimmed.
Specifically, include 32-bit binaries in «» and 64-bit binaries in «».
This may eliminate the need to include a «» in the package to create «» files for the other architecture.
How can I ensure a GUI shim?
Chocolatey 0.9.10+ will automatically detect GUI applications and adjust the shim accordingly. The detection may not always be accurate, and older versions of Chocolatey don’t handle this, so it’s best to create a «*.gui» file to direct the shim creation to be for a GUI application.
If you are creating a package and want the shim to exit immediately after calling the application, create an empty «*.gui» file next to where the exe file is (or where it will be downloaded/unpacked to), sharing the same name with the executable and appending «.gui». For example, if your file is named «», you need a file named «» (pay attention to case — «» may not work with all versions of Chocolatey).
An executable requires being run from the folder where it actually is.
Call the shim with . There are badly behaved applications that don’t run well from anywhere, and they require some extra help so they will run correctly.
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)
Committers
Committers, you should be very familiar with COMMITTERS.
Compiling / Building Source
There is a / file that creates a necessary generated file named . It must be run at least once before Visual Studio will build.
Windows
Prerequisites:
- .NET Framework 3.5 (This is a windows feature installation).
- .NET Framework 4+
- Visual Studio is helpful for working on source.
- ReSharper is immensely helpful (and there is a file to help with code conventions).
Build Process:
Run build.bat.
Running the build on Windows should produce an artifact that is tested and ready to be used.
Prerequisites:
- Install and configure Mono. Mono 5.20 or newer should work, see the Dockerfile for the currently recommended version.
# install prerequisites sudo apt install apt-transport-https dirmngr gnupg ca-certificates # add the key sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF # add the package repository # Debian 10 echo "deb https://download.mono-project.com/repo/debian stable-buster main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list # Debian 9 echo "deb https://download.mono-project.com/repo/debian stable-stretch main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list #Ubuntu 20.04 echo "deb https://download.mono-project.com/repo/ubuntu stable-focal main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list # Ubuntu 18.04 echo "deb https://download.mono-project.com/repo/ubuntu stable-bionic main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list # Ubuntu 16.04 echo "deb https://download.mono-project.com/repo/ubuntu stable-xenial main" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list # update package indexes sudo apt-get update # install sudo apt-get install mono-devel -y
- Xamarin Studio is helpful for working on source.
- Consider adding the following to your (or other relevant dot source file):
# mono # http://www.michaelruck.de/2010/03/solving-pkg-config-and-mono-35-profile.html # http://cloudgen.wordpress.com/2013/03/06/configure-nant-to-run-under-mono-3-06-beta-for-mac-osx/ export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig:/Library/Frameworks/Mono.framework/Versions/Current/lib/pkgconfig:$PKG_CONFIG_PATH
Set your permissions correctly:
chmod +x build.sh chmod +x zip.sh
Build Process:
Run ./build.sh.
Running the build on Mono produces an artifact similar to Windows but may have more rough edges. You may get a failure or two in the build script that can be safely ignored.
- Get a copy of the source code and build.
- Copy (or link) the contents of to your preferred install directory. On Linux, the preferred directory is
- Export the environment variable, pointing to the install directory the build output was copied too.
- Copy to a directory on the , rename to , and if the install directory is something else than , then edit it to point to the correct path.
Others’ repositories
- https://github.com/alanstevens/ChocoPackages
- https://github.com/AnthonyMastrean/chocolateypackages
- https://github.com/aronovgj/choco-auto
- https://github.com/chocolatey/chocolatey-coreteampackages
- https://github.com/ComFreek/chocolatey-packages
- https://github.com/ferventcoder/chocolatey-packages
- https://github.com/tunisiano187/Chocolatey-packages
- https://github.com/MarkRobertJohnson/ChocolateyPackages
- https://github.com/Redsandro/chocolatey
- https://github.com/yoshimov/chocolatey-packages
- https://github.com/adgellida/chocolateyautomaticpackages
ChocolateyGuiBranding.dll
The first time Chocolatey GUI, with the Chocolatey GUI licensed extension installed,
is executed, and the above asset files are in one of the defined locations, a new
file will be generated in the same location called .
The new file actually contains all the image files that were created, as they have
been embedded as resources within this assembly file. This approach is used in
order to optimize the loading of the assets. Once this ChocolateyGuiBranding.dll
has been created, Chocolatey GUI will use it each time the application runs. The
original image asset files are actually no longer required, and can be removed.
If at any point you need to re-generate the branding that is being used, simply
delete the following two files:
- ChocolateyGuiBranding.dll
- ChocolateyGuiBranding.resources
Then update, your image asset files, and re-run Chocolatey GUI and the branding
assembly will be re-generated.
Using a single ChocolateyGuiBranding.dll as the source of branding makes it very
simple to generate and distribute this assembly to apply branding across your
entire organisation.
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).