Installing and managing software can be a headache, especially in large organizations. But Windows Installer makes it easy. This comprehensive guide will explore everything you need to know about this invaluable tool. You’ll learn how to download Windows Installer, its key features, how to use it, and troubleshoot any issues. With this tutorial, deploying applications on Windows will be smooth and seamless.
Windows Installer is a service provided by Microsoft in the Windows operating system. It’s essential for managing software installation, removal, and maintenance on Windows-based computers. Here’s how it works:
-
Standardized Installation: Windows Installer offers a consistent format for creating installation packages for software. These packages contain all the files, settings, and instructions needed to install and set up an application.
-
Application Promotion: It allows software to be advertised for installation on a user’s system without installing it until the user decides to do so. This is useful for corporate deployment and software distribution.
-
Component Management: Windows Installer provides structured component management for applications. Components are the individual parts of an application, and Windows Installer allows precise control over their installation, repair, and removal.
-
Patch Management: Starting from Windows Installer 3.0, multiple patches can be installed in a single transaction, ensuring rollback capability if issues arise during patch installation.
-
Administrator Privileges: Users with administrator privileges can use Windows Installer’s API to query and manage product information, features, components, and patches, streamlining software management.
-
Security Features: Windows Installer 5.0 and later versions enable installation packages to define security settings for files, folders, registry keys, and new accounts, enhancing installation security.
-
Customization: Developers can create installation packages tailored for different installation contexts, whether per-machine or per-user.
-
Compatibility: It’s designed to work seamlessly with various Windows OS versions, with different redistributables available for different Windows Installer versions.
Overall, Windows Installer provides a standardized framework for software installation and management on Windows, offering reliability, security, and flexibility for software installations and updates. It’s a vital tool for developers and system administrators working with Windows-based applications.
What is Windows Installer used for?
The main function of Windows Installer is to install, maintain, and remove software on Windows computers. It uses MSI files as structured databases to ensure precise installation, accountability, and clean software removal. Windows Installer standardizes the installation process, making it reliable and efficient for users.
The essential functions and purposes of Windows Installer can be summarized as follows:
-
Simplified Application: Installation Windows Installer packages automate entire installations. Admins can deploy apps silently across an organization without disrupting users.
-
Consistent Installations: The Windows Installer service ensures installations are consistent across machines. It handles shared components between applications gracefully.
-
Version Management: Windows Installer can install multiple versions of an app side-by-side. It can also upgrade or downgrade between versions reliably.
-
Self-Repairing Installations: Installed applications are monitored by Windows Installer. It can automatically restore corrupted or missing files and repair broken installations.
-
Uninstall Capability: Windows Installer can cleanly uninstall applications and remove all associated resources with no orphan files left behind.
Versions of Windows Installer
There have been several major versions of Windows Installer over the years:
-
Windows Installer 1.0 — Released with Windows 2000. Introduced .MSI packages and the Windows Installer service.
-
Windows Installer 2.0 — Released with Windows XP. Added support for patches, cab files, and dynamic UI-level switching.
-
Windows Installer 3.0 — Released with Windows Vista. Improved restart handling, transaction support, and a reduced UI mode.
-
Windows Installer 3.1 — Released with Windows 7. Enhanced rollback support and service isolation tag for services.
-
Windows Installer 4.0 — Released with Windows Server 2008. Added compressed packages and an embedded Chainer engine.
-
Windows Installer 4.5 — Released with Windows 7 SP1. Featured a smaller and faster engine as well as side-by-side caching.
-
Windows Installer 5.0 — Released with Windows 10 and Windows Server 2016. Contains UI enhancements and support for additional MSI properties.
The latest version contains many cumulative improvements and focuses on providing robust, enterprise-grade software deployment capabilities.
Where to use Windows Installer?
Windows Installer 5.0 is included natively in Windows 11, Windows 10, Windows 8.1, Windows 8, Windows 7 SP1, Windows Server 2019, Windows Server 2016, and Windows Server 2012 R2.
So you can leverage Windows Installer for application deployment across modern Windows environments without additional requirements.
Note:
-
Older Windows versions generally contain earlier versions of Windows Installer. If needed, these can be updated by installing the appropriate Windows Installer Redistributable package.
How to obtain the Windows Installer Redistributable (4.5 and earlier)
Here are the steps to download and install the redistributable on your system:
Step 1: Go to the Microsoft Download Center at: https://www.microsoft.com/en-us/download
Step 2: Search for “Windows Installer Redistributable 4.5”
Step 3: Select the appropriate Redistributable package for your Windows version:
Step 4: Click Download.
Step 5: Choose all packages and click Next.
Step 6: Install all the packages on your system.
Step 7: Restart the machine after installation. Windows Installer will now be updated.
Why does my Windows installer show errors?
Some common reasons for Windows Installer errors include:
-
Corrupted system files: The Windows Installer relies on core system files and components. If any are damaged, it can cause errors.
-
Incompatible applications: Sometimes installed apps use older versions of shared libraries that clash. This results in installer issues when updating or adding new apps.
-
Incomplete installations: If an installation gets interrupted halfway, it can leave behind an unfinished setup from which the installer cannot recover.
-
Insufficient privileges: The Windows Installer requires admin access to function correctly. Errors can occur if executed under a limited user account.
-
Conflicts with other software: Antivirus, firewall, VPN clients, etc., sometimes clash with the installer service causing various errors.
If you face Windows Installer errors, some troubleshooting steps are:
-
Try restarting the system and rerunning the installation. This resets various components involved.
-
Update Windows and any applications to their latest versions. This solves many version-related conflicts.
-
Run scans such as DISM and SFC to fix corrupted system files causing issues.
-
Disable other background software temporarily to check for conflicts.
-
Install the application in a different directory away from existing installations.
-
Grant full admin access to the Windows Installer service.
With some dedicated troubleshooting, you can resolve most installer errors and get applications deployed smoothly.
Choose new office software – WPS Office
WPS Office is a free and open-source office suite that is fully compatible with Microsoft Office files. It offers lightweight yet powerful alternatives to Word, Excel, PowerPoint, and other productivity tools.
Here are some of its notable features and advantages:
-
Free to download and use indefinitely, both for personal and commercial purposes
-
Supports the latest DOC, DOCX, XLS, PPT, PPTX, and other Microsoft Office formats
-
Very small installer size (~150MB) and low memory usage compared to Office
-
Inbuilt PDF converter, OCR scanning, screen recording, and other handy tools
-
Clean and intuitive interface with support for multiple themes
-
Available on Windows, Linux, macOS, Android and iOS
-
Secure encryption and full privacy for your documents
-
Seamless cloud connectivity and multi-device sync via WPS Cloud
-
Hundreds of free templates, fonts, themes, and other resources are available
WPS Office is a free alternative to Microsoft Office that offers all the essential editing and document management capabilities for basic home and student use. It is a lightweight app that is quicker to load and smoother for older laptops. For users who do not need the advanced functionality or enterprise-wide deployment of Microsoft Office, WPS Office is a great option.
How to Download WPS Office for Free?
The installation is effortless and straightforward:
Step 1: Go to https://www.wps.com/download/ and click the Free Download button.
Step 2: The browser will download the WPS Office installer package based on your selection.
Step 3: Once downloaded, run the WPS installer.
Step 4: Click Install Now and follow the setup wizard prompts to install WPS Office on your PC.
WPS Office is now installed and ready to use! The application can be launched from the Start Menu like any other program.
Trustpilot4.8
WPS Office- Free All-in-One Office Suite
-
Use Word, Excel, and PPT for FREE, No Ads.
-
Edit PDF files with the powerful PDF toolkit.
-
Microsoft-like interface. Easy to learn. 100% Compatibility.
-
Boost your productivity with WPS’s abundant free Word, Excel, PPT, and CV templates.
Algirdas Jasaitis
logo
FAQs
Is Windows Installer compatible with all Windows versions?
Windows Installer is supported on Windows 2000 and above. Older Windows versions like 95/98 may need compatibility updates for full installer support.
Does Windows Installer work with 64-bit architectures?
Yes, Windows Installer functions seamlessly on both 32-bit and 64-bit Windows platforms. Separate 32-bit and 64-bit packages can also be created.
Summary
Windows Installer is an indispensable package management system for streamlining software deployment on the Windows desktop. This comprehensive guide provided an overview of its functionality, versions, usage scenarios, and troubleshooting tips. We also explored WPS Office as a great free alternative to Microsoft Office for basic home and student needs. With this tutorial, you should have a deeper understanding of leveraging Windows Installer and WPS Office for your software installation needs.
Время на прочтение7 мин
Количество просмотров55K
Технология Windows Installer (MSI) является стандартом де-факто в мире системных администраторов, занимающихся распространением и поддержкой программного обеспечения для десктопных и серверных версий Windows. Формат MSI поддерживается всеми крупнейшими системами управления конфигурациями (Microsoft SCCM, CA Unicenter и многими другими), а для некоторых систем распространения ПО — является единственным поддерживаемым форматом.
Мой опыт работы с этой технологией — как теоретический, так и практический — приобретен за время работы в компании «Инфопульс Украина» и связан с созданием MSI-пакетов и подготовкой готовых MSI-пакетов к автоматической установке в корпоративной среде.
Зачем это вам?
Если вы занимаетесь централизованной установкой приложений в сетях Windows, знание формата MSI и умение создавать и редактировать пакеты в этом формате вам может здорово пригодиться при подготовке пакета к развертыванию и диагностике проблем. В Европе и США технология Windows Installer востребована многими крупными заказчиками, поэтому знание MSI может быть плюсом для системного администратора при трудоустройстве.
Что нужно знать и уметь перед началом изучения?
Ничего сложного. Если у вас есть опыт администрирования и поддержки небольшой (а лучше большой, иерархической) сети Windows-машин, вероятнее всего вы уже сталкивались с основными вопросами и понятиями, которые вам понадобятся. Перед тем, как начать, убедитесь, что вы хорошо понимаете структуру файловой системы Windows, структуру профиля пользователя и структуру реестра, знаете что такое процессы и службы в Windows, умеете управлять учетными записями пользователей и знаете где находятся журналы событий. Для того, чтобы научиться создавать пакеты MSI, вам совсем необязательно иметь опыт разработчика, хотя конечно лучше если такой опыт у вас есть. И совсем не обязательно уметь писать запросы на SQL, хотя это тоже может пригодиться (ведь каждый MSI-файл — это небольшая реляционная база данных). Но обязательно нужно уметь читать и понимать техническую документацию на английском, без этого скорее всего ничего не получится. При изучении теории (и при создании пакетов на практике) постарайтесь хотя бы на первых порах строго следовать стандартам Windows Installer, избегая вспомогательных утилит типа InstallShield/InstallScript, так вы лучше поймёте как правильно создать MSI-пакет.
Готовим песочницу и начинаем практику
Начать нужно с установки и настройки виртуальной машины. В процессе обучения вам придется немало поэкспериментировать, поэтому лучше сделать это в песочнице. Если нужны бесплатные продукты — устанавливаем VirtualBox или VMWare Player (для профессиональных задач их функционала может быть недостаточно, но для обучения — вполне подойдет). В виртуальной машине, естественно, нужно установить Windows на ваш выбор (XP и выше).
Если у вас уже есть опыт работы с утилитами от Sysinternals — прекрасно. Если нет — самое время восполнить пробел. Нам понадобятся минимум две: для отслеживания файловой и реестровой активности приложения при установке или во время его работы — Process Monitor, для запуска инсталляции от имени учетной записи LocalSystem — PsExec. Попрактикуйтесь использовать эти утилиты на простом приложении типа notepad (с какими ресурсами работает notepad при открытии файла, при сохранении файла; запустите notepad от имени пользователя LocalSystem, поэкспериментируйте с сохранением файлов и установкой файловых ассоциаций), в дальнейшем эти навыки пригодятся.
Установите Panda QuickShot или другой софт для сравнения состояний системы. Разберитесь с основным функционалом, научитесь отслеживать файловые и реестровые изменения в системе при установке нового приложения или изменении параметров системы (самое простое — зарегистрируйте новую файловую ассоциацию для notepad, измените обои рабочего стола и отследите где хранятся эти настройки). Подойдите к этому творчески, поле для экспериментов обширное.
Скачайте MSI-инсталлятор какого-нибудь несложного приложения (например, Orca, InstEd или Firefox). Установите пакет на виртуальной машине, с помощью описанных выше утилит изучите устанавливаемые им ресурсы. Научитесь пользоваться командной строкой Windows Installer (msiexec /?), поэкспериментируйте с различными опциями установки и сравните результат. Выполните удаление приложения из командной строки, установите пакет в автоматическом (silent) режиме.
Установите InstEd или Orca на хост-машине. Откройте MSI-пакет, который вы устанавливали на виртуальной машине, с помощью одной из этих утилит. Сравните записи основных таблиц в MSI-пакете (File, Directory, Registry) с ресурсами (файлы, папки, ключи реестра), установленными этим пакетом на вашей виртуальной машине (результат сравнения снимков состояний с помощью Panda QuickShot).
Немного теории
Теперь самое время взяться за теорию. Не буду дублировать официальную документацию и отдельные полезные статьи по ссылкам ниже, просто попробую перечислить вещи, с которыми нужно разобраться для начала:
- Таблица Property, код продукта (ProductCode), код пакета (PackageCode), стандартные свойства в MSI;
- Таблица Upgrade и код обновления (UpgradeCode);
- Таблицы Feature, Component и их назначение;
- Таблицы Directory, File, Registry, Shortcut;
- Способы хранения файлов приложения, поставляемых с MSI-пакетом, таблица Media;
- Трансформы, их создание и применение из командной строки.
Прочтение документации по указанным темам подкрепляйте экспериментами на готовых пакетах, а со временем можно попробовать сделать пакет самому. Этих знаний вам будет достаточно для внесения небольших изменений в MSI-пакеты при подготовке к развертыванию в корпоративной среде (типовые задачи — задание свойств пакета, правка реестра, удаление файлов и ярлыков, отключение кнопки Remove для приложения в Add/Remove Programs). Только не забывайте после внесения любых правок в пакет выполнять тщательное тестирование перед запуском пакета в промышленную эксплуатацию. При тестировании обязательно используйте рекомендации, приведенные в этой статье.
Думаю, на этом пока можно закончить вводную часть. В дальнейшем (если будет интерес) я попробую рассказать об особенностях некоторых готовых MSI-пакетов, предоставляемых производителями ПО для развертывания в корпоративной среде и рассмотреть другие интересующие системных администраторов вопросы.
Пожелания, замечания, а также предложения по темам для следующих статей приветствуются.
Обзор утилит и документации
Бесплатно можно использовать простые редакторы MSI-файлов с ограниченным функционалом — здесь упоминания заслуживают классическая Orca от Microsoft и довольно удобный InstEd. Эти редакторы позволяют вносить небольшие изменения в готовые MSI-файлы, создавать и применять трансформы, но создавать в них MSI-пакеты с нуля довольно непросто (а для больших пакетов — и вовсе не имеет смысла). Но если вы действительно хотите изучить технологию MSI, вам просто необходимо собрать пару простых пакетов в InstEd или Orca и выполнить их валидацию на соответствие стандарту Windows Installer.
Специализированные утилиты для выполнения setup capture (создания или конвертирования установочных пакетов из так называемых «старых форматов»» в формат MSI с использованием сравнения «снимков» системы до и после установки приложения или мониторинга изменений в системе «на лету») — бесплатный AppDeploy Repackager, или более серьезный MSI Generator. MSI-пакетам, созданным с использованием этих утилит, может потребоваться некоторая доработка, которую можно выполнить с помощью редактора MSI.
Серьёзные полнофункциональные (и весьма дорогие) IDE, обеспечивающие поддержку полного цикла работ с MSI-пакетами — если вы будете заниматься технологией MSI профессионально, вам скорее всего не обойтись без этих программ. В этом сегменте до недавнего времени доминировали два продукта — AdminStudio от Flexera и Wise Package Studio от Symantec, но недавно Symantec объявил о прекращении работ по развитию Wise Package Studio, и рынок переходит в руки Flexera. Кроме работы с MSI, AdminStudio позволяет работать с виртуальными пакетами форматов Microsoft App-V, VMware Thin App и Citrix XenApp. Для ознакомительных целей доступна пробная 21-дневная версия.
Отдельно стоит упомянуть WIX (Windows Installer XML) — набор утилит для создания MSI-файлов из XML-описаний. Этот проект был выпущен «Майкрософтом» под открытой лицензией Common Public License, поддерживает интерфейс командной строки и может использоваться для автоматизации создания версий инсталляционных пакетов. Хорошее описание есть на Хабре.
Полезные ресурсы:
Статьи по Windows Installer на RSDN: раз, два. Хороши тем, что описывают основные концепции и понятия MSI на русском языке и в довольно читабельной форме. Статьи немного устарели (описывают стандарт 2.0), но актуальности не потеряли. Важно понимать, что только этих статей для изучения MSI недостаточно — нужно много читать MSDN и много практиковаться.
Статьи на MSDN — самый полный источник информации, которая понадобится в процессе изучения и дальнейшей работы. Присутствуют пошаговые упражнения для практики по созданию MSI-пакетов с нуля.
AppDeploy.com — общедоступная база знаний по приложениям, часто можно найти особенности установки или настройки готовых пакетов, выпускаемых крупными вендорами (Adobe, Microsoft), командные строки для автоматизации установки и другие полезные вещи.
Для удобства продублирую ссылки на программы из текста одним списком:
- Виртуальные машины: VirtualBox или VMWare Player.
- Утилиты Sysinternals: Process Monitor, PsExec, полный список утилит с описаниями.
- Программы для редактирования MSI-файлов: InstEd, Orca (нужно устанавливать как часть Windows 7 SDK).
- Программы для создания MSI-файлов: AppDeploy Repackager, MSI Generator, AdminStudio (пробная версия).
Windows Installer
Purpose
Microsoft Windows Installer is an installation and configuration service provided with Windows. The installer service enables customers to provide better corporate deployment and provides a standard format for
component management. The installer also enables the advertisement of applications and features according to the
operating system. For more information, see
Platform Support of Advertisement.
This documentation describes Windows Installer 5.0 and earlier versions. Not all the
capabilities available in later Windows Installer versions are available in earlier versions. This documentation
does not describe versions earlier than Windows Installer 2.0. Installation packages and patches that are created for Windows Installer 2.0 can still be
installed by using Windows Installer 3.0 and later.
Windows Installer 3.0 and later, can install multiple patches with a single
transaction that integrates installation progress, rollback, and reboots. The installer can apply patches in a
specified order regardless of the order that the patches are provided to the system. Patching using Windows Installer 3.0
only updates files affected by the patch and can be significantly faster than earlier installer versions. Patches installed with Windows Installer 3.0 or later can be uninstalled in any order to leave the state of the
product the same as if the patch was never installed. Accounts with administrator privileges can use the API of Windows Installer 3.0 and later to query
and inventory product, feature, component, and patch information. The installer can be used to read, edit, and replace source
lists for network, URL, and media sources. Administrators can enumerate across user and install contexts, and
manage source lists from an external process.
Windows Installer 4.5 and later can install multiple installation packages using transaction processing. If all the packages in the transaction cannot be installed successfully, or if the user cancels the installation, the Windows Installer can roll back changes and restore the computer to its original state. The installer ensures that all the packages belonging to a multiple-package transaction are installed or none of the packages are installed.
Beginning with Windows Installer 5.0, a package can be authored to secure new accounts, Windows Services, files, folders, and registry keys. The package can specify a security descriptor that denies permissions, specifies inheritance of permissions from a parent resource, or specifies the permissions of a new account. For information, see Securing Resources. The Windows Installer 5.0 service can enumerate all components installed on the computer and obtain the key path for the component. For more information, see Enumerating Components. By Using Services Configuration, Windows Installer 5.0 packages can customize the services on a computer. Setup developers can use Windows Installer 5.0 and Single Package Authoring to develop single installation packages capable of installing an application in either the per-machine or per-user installation context.
Where Applicable
Windows Installer enables the efficient installation and configuration of your products and applications. The
installer provides new capabilities to advertise features without installing them, to install products on demand,
and to add user customizations.
Developer Audience
This documentation is intended for software developers who want to make applications that use Windows Installer.
It provides general background information about installation packages and the installer service. It contains
complete descriptions of the application programming interface and elements of the installer database. This
documentation also contains supplemental information for developers who want to use a table editor or a package
creation tool to make or maintain an installation.
Run-Time Requirements
Windows Installer 5.0 will be released with, and require Windows Server 2008 R2 or Windows 7. Versions earlier than Windows Installer 5.0 were released with Windows Server 2008, Windows Vista, Windows Server 2003,
Windows XP, and Windows 2000.
Windows Installer 4.5 requires Windows Server 2008, Windows Vista, Windows XP with Service Pack 2 (SP2) and later, and Windows Server 2003 with Service Pack 1 (SP1) and later.
Windows Installer 4.0 requires Windows Vista or Windows Server 2008. There is
no redistributable for installing Windows Installer 4.0 on other operating systems. An updated
version of Windows Installer 4.0, which does not add any new features, is available in
Windows Vista with Service Pack 1 (SP1) and Windows Server 2008.
Windows Installer 3.1 requires Windows Server 2003, Windows XP, or
Windows 2000 with Service Pack 3 (SP3).
Windows Installer 3.0 requires Windows Server 2003, Windows XP, or
Windows 2000 with SP3. Windows Installer 3.0 is included in
Windows XP with Service Pack 2 (SP2). It is available as a redistributable for Windows 2000 Server with Service Pack 3 (SP3) and
Windows 2000 Server with Service Pack 4 (SP4), Windows XP RTM and Windows XP with Service Pack 1 (SP1), and
Windows Server 2003 RTM.
Windows Installer Redistributables
are available for Windows Installer 4.5 and earlier versions. There is no redistributable available for Windows Installer 4.0.
Windows Installer 2.0 is contained in Windows Server 2003 and Windows XP.
Windows Installer 2.0 is available as a package for installing or upgrading to Windows
Installer 2.0 on Windows 2000. This package should not be used to install or
upgrade Windows Installer 2.0 on Windows Server 2003 and Windows XP.
You can find all the available Windows Installer redistributables at the
Microsoft Download Center.
In This Section
Topic | Description |
---|---|
Roadmap |
A guide to Windows Installer documentation. |
Overview |
General information about the installer. |
What’s New in Windows Installer |
Lists additions and changes to Windows Installer. |
Reference |
Documentation of Windows Installer functions. |
Windows Installer Scripting Examples |
Windows Installer examples using script. |
Send comments about this topic to Microsoft
Build date: 8/13/2009
© 2009 Microsoft Corporation. All rights reserved.
Устройство и развертывание пакетных файлов
Какому администратору Windows не знакомы символы msi? Служба Windows Installer (программа msiexec.exe) и ее пакетный файл .msi — фактически стандартная технология для установки приложений Windows. Преимущества пакета установки приложений Windows Installer общеизвестны. Во-первых, при сбоях в процессе установки пакет .msi отменяет выполненный фрагмент установки и восстанавливает исходное состояние компьютера, тем самым предотвращая повреждения приложений и системы. Во-вторых, .msi-упакованное приложение обладает способностью к самовосстановлению, если пользователь удаляет один из его файлов. И наконец, Windows Installer обеспечивает установку программ на пользовательских компьютерах. Основные принципы работы Windows Installer широко известны, но более глубокое понимание внутренних механизмов Windows Installer и пакетов .msi позволит строить специализированные пакеты установки приложений и упростит диагностику сбоев в процессе развертывания. Ниже приводится обзор технологии Windows Installer, а затем речь пойдет о структуре пакетов .msi и их взаимодействии со службой Windows Installer.
Технология Windows Installer
Технология Windows Installer была разработана около четырех лет назад, а позднее стала базовым компонентом операционной системы Windows 2000 Server. Windows Installer 2.0 входит в состав Windows Server 2003 и Windows XP и поддерживает сборки Microsoft .NET (блок установки в .NET). Пользователи могут получить Windows Installer либо вместе с операционной системой Windows в качестве службы Windows Installer, либо в составе комплекта разработки программ (software development kit, SDK). Служба Windows Installer представляет собой механизм, который устанавливает пакеты Windows Installer (.msi-файлы). SDK содержит спецификации и API, определяющие формат и функцию .msi-файлов. Windows Installer SDK представляет собой составную часть Platform SDK. Его можно загрузить по адресу http://www.microsoft.com/msdownload/platformsdk/ sdkupdate/sdkinfo.htm. Разработчики и поставщики инструментов упаковки программ, такие как InstallShield Software, OnDemand Software и Wise Solutions (в настоящее время подразделение компании Altiris), применяют SDK для подготовки пакетов установки приложений. Программисты часто используют инструменты упаковки приложений, которые преобразуют старые процедуры установки в формат Windows Installer, чтобы скрыть от пользователей сложность технологии Windows Installer.
Продукты, функции и компоненты
.msi-файл представляет собой сложную базу инструкций по установке приложений, которая содержит десятки таблиц, сотни столбцов и иногда вложенные файлы. В базе данных хранится информация о требованиях операционной системы к установке приложения, этапах установки и даже диалоговых окнах, выводимых на экран.
.msi-файл имеет трехуровневую структуру. Высший уровень — продукт, собственно приложение. Продукту присваивается уникальный код — глобально уникальный идентификатор (globally unique identifier, GUID). На следующем уровне располагаются функциональные блоки внутри продукта. Функциональные блоки имеют имена и могут быть добавлены по желанию пользователя. На экране 1 показан пример функциональных блоков в приложении — в данном случае Microsoft Office Access и Microsoft Office Excel в пакете установки Microsoft Office. Функциональный блок — это единый блок для установки внутри пакета Windows Installer. Устанавливаются (или удаляются) функциональные блоки пакета, а не отдельные файлы.
Экран 1. Функциональные блоки приложения, упакованного для Windows Installer |
На экране 1 видно, что Excel состоит из множества функциональных подблоков, таких как Help и Spreadsheet Templates. Во время установки пользователь может указать подблоки, которые следует установить на компьютере локально или запускать с сервера, добавить при первом обращении к ним (обозначается единицей в пиктограмме подблока) или вообще не требуется устанавливать. Метод «объявления» (advertisement) подблоков описан по врезке «Возможности объявлений».
Функциональные блоки состоят из компонентов, которые представляют третий уровень иерархии .msi-файла. Компонент — это базовая единица пакета Windows Installer и строительный блок приложения. Компонент может быть файлом или группой файлов, параметром реестра, ярлыком или ресурсом (например, пиктограммой). С компонентом связан ключевой путь (key path). Ключевой путь определяет файл или параметр, без которого невозможна полная установка компонента. Ключевой путь — основа механизма самовосстановления пакетов на базе Windows Installer. При ремонте .msi-упакованного приложения служба Windows Installer проверяет полноту всех ключевых путей компонентов. Если ключевой путь какого-нибудь компонента отсутствует, служба Windows Installer определяет, какому функциональному блоку принадлежит компонент, и повторно устанавливает функциональный блок. Таким образом, время, необходимое для ремонта развернутого приложения, отчасти зависит от числа компонентов в пакете и числа компонентов в функциональном блоке, содержащем испорченный компонент.
База данных Windows Installer
Как отмечалось ранее, .msi-файл представляет собой набор инструкций по установке, организованных в таблицы. Windows Installer SDK определяет каждую таблицу и столбец. С помощью редактора баз данных Orca из Windows Installer SDK можно просматривать и редактировать содержимое .msi-файла. .msi-файл установки для Orca находится в подкаталоге in установочного каталога Platform SDK (например, c:program filesplatform sdkin). После установки Orca можно открыть любой .msi-файл. В левой панели интерфейса Orca представлен список таблиц файла. Выделив таблицу, в правой панели можно увидеть ее строки и столбцы.
Экран 2. Таблицы базы данных приложения, упакованного для Windows Installer |
На экране 2 показана таблица LaunchCondition пакета Windows Installer для Group Policy Management Console (GPMC). В правой панели таблицы представлены минимальные требования к операционной системе и платформе для установки GPMC. В столбце Condition содержатся условия, которые должны быть выполнены в процессе установки. В столбце Description описаны минимальные требования для набора условий. Приступая к установке приложения, Windows Installer проверяет, удовлетворены ли условия запуска, прежде чем продолжить установку.
Таблицы последовательностей (sequence table) представляют собой ядро базы данных; в них перечислены действия, которые служба Windows Installer должна выполнить в процессе установки, и порядок их выполнения. Например, в таблице последовательностей указывается, что механизм Installer должен сначала проверить условия запуска в таблице LaunchCondition, затем скопировать исходные файлы в каталог назначения и подготовить набор элементов реестра. Таблицы последовательностей бывают трех типов: Admin, Advertisement и Install. Тип таблицы последовательностей, используемый Windows Installer, зависит от типа выполняемой процедуры установки. Описания типов таблиц последовательностей даны в таблице 1.
С каждой таблицей последовательностей связаны две вспомогательные таблицы. Одна из них — InstallUISequence — определяет диалоговые окна пользовательского интерфейса, которые должны отображаться при интерактивной (управляемой пользователем) установке. Другая таблица — так называемая таблица «исполнительной последовательности» (execute sequence; InstallExecuteSequence) — определяет шаги, необходимые для установки.
Последовательность состоит из набора заранее определенных стандартных функций, которые перечислены в столбце Action таблицы InstallExecuteSequence. Стандартные функции выполняют разнообразные задачи, в том числе копирование файлов, поиск новых версий программы и определение размера дискового пространства, доступного при установке. В документации SDK и Orca приведены подробные сведения о назначении конкретного пакета Windows Installer. С помощью Orca можно подготовить специальные операции для задач, которые нельзя решить с использованием стандартных функций пакета Windows Installer. Специальная операция может быть DLL, составленной пользователем, и даже сценарием VBScript для таких действий, как поиск в Active Directory (AD) определенных значений перед продолжением установки.
Таблица Property — еще одна важная часть базы данных .msi. Свойства представляют собой постоянные величины, задавая которые можно управлять ходом установки. В сущности, свойства есть переменные среды для .msi-файла. В пакетах Windows Installer часто используется свойство ALLUSERS, которое указывает процедуре установки, каким образом хранится информация о конфигурации приложения — для пользователя или для компьютера. Имена свойств чувствительны к регистру и их можно указывать в командной строке во время установки или используя трансформацию.
Трансформации, исправления и модули слияния
.msi-файл, полученный от поставщика, часто не располагает всем необходимым для развертывания пакета в конкретной среде. Например, потребитель может пожелать развернуть пакет автоматически с помощью инструмента развертывания программного обеспечения или установить только определенные функциональные блоки. В такой ситуации могут пригодиться трансформации. Трансформация — это специальный тип файла базы данных .msi, обычно имеющего расширение .mst. Трансформации применяются к процедуре развертывания приложения во время установки. В сущности, они изменяют выбираемые по умолчанию значения в пакете .msi, управляя процессом установки. Измененные значения в .msi-файле не сохраняются; они просто определяют, как будет протекать конкретная установка.
Файлы исправлений (patch file или .msp-файлы) отличаются от трансформаций. Как правило, поставщик выпускает файл исправлений, когда нужно модернизировать продукт, не прибегая к его глубокой переработке. Примером исправлений могут служить обновления для системы безопасности. После установки исправления в экземпляре .msi-файла, хранящемся в кэше рабочей станции, производятся постоянные изменения. Чтобы новые пользователи в будущем получали обновленные файлы, следует применить файлы исправлений к исходному пакету приложения.
Еще один вариант .msi-файла — модуль слияния (merge module, или .msm-файл), набор компонентов, многократно используемых при установке приложений. Например, в различных программах независимых поставщиков применяются компоненты Microsoft Data Access Components (MDAC). Вместо того чтобы воспроизводить установку общих компонентов в каждом новом .msi-пакете, авторы пакетов приложений могут задействовать модули слияния, предоставляемые поставщиками общих компонентов. Модули слияния — упрощенные файлы базы данных .msi, содержащие только общие функциональные блоки и компоненты для процедур установки приложений. Часто собственно компонентные файлы встраиваются в .msm-файл, что позволяет использовать модули слияния с разными пакетами. Затем .msm-файлы вставляются в основной пакет Windows Installer для данного приложения на этапе создания пакета.
При подготовке нового пакета установки файлы приложения можно вставить в .msi-файл. Как правило, файлы вставляются в виде встроенных файлов .cab, которые представляют собой сжатые наборы файлов, похожие на .zip-файлы. В .msi-файл удобно вставлять .cab-файлы не очень большого размера. Например, в Office имеются отдельные .msi- и .cab-файлы, так как размеры .cab-файлов Office достигают нескольких сотен мегабайт. Однако, упаковав все необходимые файлы малого приложения в .msi-файл, можно получить компактный файл, который удобно распространять среди пользователей. Извлечь встроенный .cab-файл из .msi-файла можно с помощью инструмента msidb.exe пакета Windows Installer SDK.
Служба Windows Installer
Пакеты Windows Installer и служба Windows Installer взаимозависимы: они не могут существовать друг без друга. Служба Installer по умолчанию устанавливается на всех компьютерах с версиями операционной системы, выпущенными после Windows 2000: редистрибутивную версию (автономную версию службы Installer и сопутствующие DLL) можно развернуть на компьютерах Windows NT Server 4.0 и Windows 9x. Служба Installer работает в контексте привилегированной пользовательской учетной записи LocalSystem. Чтобы запустить службу Windows Installer, нужно дважды щелкнуть на .msi-файле (например, в Windows Explorer); при запуске службы формируется новый процесс Installer (msiexec.exe) в контексте полномочий пользователя. После того как Windows Installer завершит установку приложения, служба Installer закрывается до следующего обращения к ней.
Служба Windows Installer обеспечивает набор функций, удобных для развертывания программ, особенно при использовании совместно с функцией Software Installation в Group Policy. Главная среди этих функций — повышение полномочий (privilege escalation). Когда обычный пользователь пытается установить приложение на своем компьютере, дважды щелкнув на .msi-файле, его полномочий для выполнения установки не всегда достаточно. Однако при развертывании приложения с помощью функции Software Installation групповой политики служба Windows Installer выполняет установку в своем контексте безопасности LocalSystem.
В частности, служба Installer создает новый процесс msiexec.exe в контексте безопасности пользователя для выполнения той части установки, которая проводится в пользовательском профиле. Служба Installer использует собственный повышенный контекст безопасности (учетную запись LocalSystem) для выполнения специфической для данного компьютера части процедуры установки, для проведения которой у пользователя полномочий нет. Приложения, развернутые таким способом, называются управляемыми (managed applications). Повышение полномочий, используемое Windows Installer для управляемых приложений, как правило, возможно только при применении групповой политики, хотя метод доступен и вне процедур на базе Group Policy Object (GPO), через политику Administrative Template.
В рамках взаимозависимых отношений между Group Policy и службой Windows Installer реализованы объявления (advertisement). Как отмечалось ранее, при связывании программы с пользователем в Group Policy, в сущности, производится установка с объявлением. Таким образом, механизм Windows Installer обрабатывает сценарий объявления приложения (файл .aas), а не непосредственно .msi-файл. Файл .aas создается, когда для развертывания приложения используется Group Policy. Чтобы создать .aas-файл, редактор Group Policy Editor (GPE) вызывает функцию, экспортируемую из msi.dll (основная DLL, используемая msiexec.exe), которая генерирует уникальный сценарий объявлений внутри GPO. Таким образом, когда механизм Windows Installer обрабатывает сценарий объявлений, ему известно местонахождение соответствующего .msi-файла и части приложения, которые нужно объявить. Другими словами, процедура установки программ на базе GPO тесно связана со службой Windows Installer и наоборот.
Хранение файлов Installer на рабочей станции
Рассмотрим, что происходит на рабочей станции, когда служба Windows Installer устанавливает пакет .msi. Во-первых, чтобы обеспечить отмену действий в случае сбоя, Installer делает резервные копии всех замененных файлов, сохраняя их во временной папке на жестком диске пользователя, обычно C:config.msi. Заглянув в эту папку в ходе установки, можно увидеть в ней временные файлы с необычными именами, созданные службой Installer. После завершения установки служба Installer удаляет временные файлы.
Закончив установку, Windows Installer сохраняет экземпляр ассоциированного .msi-файла и любые трансформации, использовавшиеся Windows Installer при установке приложения, в папке \%windir%installer, назначая файлам уникальные условные имена (например, 19fe9b79.msi). Файлы в \%windir%installer в действительности представляют собой кэшированные копии всех .msi-файлов, обработанных службой Windows Installer на компьютере. Благодаря наличию кэшированных копий пользователь может изменить или удалить приложение, не обращаясь к оригинальному пакету установки, который может находиться на разделяемом диске сервера, недоступном мобильному пользователю. Windows отслеживает все развернутые приложения на базе .msi; имеющиеся функциональные блоки, компоненты и исправления, а также имя кэшированного .msi-файла в реестре.
Чтобы выяснить, какой .msi-файл с непонятным именем соответствует данному приложению на рабочей станции, следует перейти в раздел реестра HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows CurrentVersionInstallerUserData. Разделы упорядочены по SID имени пользователя; первой показана учетная запись LocalSystem, S-1-5-18, далее обычно перечисляются все приложения, установленные на компьютере. Список доступных пользователю программ приведен под соответствующим SID пользователя.
Запуск Installer Files из командной строки и в сценариях
Существует два дополнительных способа запуска пакетных установок Windows Installer — из командной строки и сценария. С помощью msiexec.exe можно выполнять различные процедуры установки из командной строки. Полный список функций командной строки для msiexec.exe приведен в статье Microsoft «Command-Line Switches for the Microsoft Windows Installer Tool» по адресу http://support.microsoft.com/?kbid=227091. Например, из командной строки можно установить один функциональный блок в прикладном пакете, такой как инструменты консоли DNS в пакете Windows 2003 Administration Tools (adminpak.msi). С помощью Orca следует отыскать нужное имя функционального блока — в данном случае FeDNSConsole — и запустить msiexec.exe из командной строки, чтобы произвести установку:
msiexec /I adminpak.msi ADDLOCAL=FeDNSConsole
Свойство ADDLOCAL используется данной командой, чтобы указать службе Windows Installer функциональные блоки пакета, которые необходимо установить. Метод командной строки используется вместо выбора функциональных блоков пользователями или установки отдельных блоков администратором с помощью файла трансформации.
В Windows Installer SDK имеются примеры, поясняющие использование сценариев Windows Script Host (WSH) для взаимодействия со службой Windows Installer и пакетами .msi. Объект WindowsInstaller.Installer располагает методами и свойствами, которые можно применять в сценариях для выполнения таких операций, как подготовка списка всех .msi-пакетов, имеющихся в системе, добавление .cab-файла в базу данных .msi, применение трансформации в ходе установки и сравнение двух .msi-файлов базы данных. Более подробную информацию о сценарных объектах Windows Installer можно получить, изучив сценарии примеров Installer SDK в папке http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/using_the_automation_interface.asp.
Как было показано выше, задачи Windows Installer не ограничиваются простым щелчком на .msi-файле. Мощная технология Windows Installer позволяет гибко и быстро устанавливать программы, но для эффективного использования службы необходимо понимать принципы ее работы.
Даррен Мар-Элиа — редактор журнала Windows & NET Magazine. С ним можно связаться по адресу: dmarelia@winnetmag.net
Возможности объявлений
Объявление приложений — компонент Windows Installer, который широко используется при развертывании приложений с помощью Group Policy. Объявленное приложение на самом деле не устанавливается на настольном компьютере пользователя, обозначается лишь «присутствие» приложения. Это может быть ярлык на рабочем столе или в меню Start, ассоциирование файлов в реестре и даже COM-компонент, зарегистрированный в HKEY_CLASSES_ROOT. Объявление оповещает пользователя о том, что приложение установлено и готово к использованию. Однако сами файлы приложения разворачиваются лишь после первого обращения пользователя к приложению. Преимущество объявлений заключается в том, что приложения доступны, но устанавливаются лишь после того, как в них возникает необходимость. Благодаря объявлениям, администратору, обслуживающему 20 тыс. настольных компьютеров, приходится обновлять приложения только на компьютерах, пользователи которых действительно работают с этими программами. Недостаток объявлений — вынужденное ожидание в течение нескольких минут, пока система устанавливает приложение для первого запуска.
Типы таблиц последовательностей
Тип таблицы последовательностей | Описание |
Admin | Используется для административных установок приложений (с сервера) |
Advertisement | Используется для установки с объявлениями |
Install | Используется для интерактивных или автоматических установок на локальном компьютере — наиболее распространенный тип |
InstallShield Tips and Tricks
Get Started with InstallShield
CONTENTS
- Windows Installer – Get Started with InstallShield
- Create a Windows Installer project – Basic MSI Project
- Advanced Windows Installer Capabilities
- Installation Information
- Adding Files and Folders to your Windows Installer
- Configure Prerequisites for your Windows Installer
- Create and Configure Shortcuts
- Adding multiple languages to your Windows Installer package
- Digitally Sign your Windows Installer package
- Integration with Visual Studio
- Build MSIX Packages with InstallShield
- Build your installers from within Azure DevOps pipelines
Windows Installer – Get Started with InstallShield
Windows Installer or MSI Installer is a Microsoft defined standard package for the installation, maintenance, and removal of software on modern Microsoft Windows systems. It provides a consistent experience for software developers/vendors to package their software for distribution and installation on Windows systems irrespective of which version it’s being installed on.
Windows Installer uses a database-like file called a Windows Installer Package (MSI) to describe the installation process, including what files and registry settings need to be created, modified, or deleted during installation and uninstallation. When you run an MSI file, Windows Installer takes care of installing the software, checking for prerequisites, and configuring the system as needed.
Windows Installer is built into Windows operating systems since Windows 2000 and has been the installation format of choice for many popular software applications.
In this section, we will understand how to get started with creating a Windows Installer using InstallShield. InstallShield supports several project types, but as you can understand, the most popular one is to create a Windows Installer using the Basic MSI Project
Create a Windows Installer project – Basic MSI Project
Creating your first Windows Installer setup from InstallShield can be done in 3 simple steps
1. Create a Basic MSI Project
2. Add files in the ‘Files and Folders’ view
3. Build the project using the options available in the toolbar/ribbon
You can also refer to the short video that depicts this process
Once the build process is complete, you can launch your Windows Installer setup by navigating to the release folder or by simply running the ‘Run’ option in the toolbar/ribbon.
However, most software applications are not as simple as adding a file. In the following sections, let’s explore some of advanced capabilities that you’d like your installer to do.
Advanced Windows Installer Capabilities
Installation Information
InstallShield stores your project settings in a single installation project file (.ism file). This file stores all of the information about your project. In the General Information view, you can edit basic information about your installation project—including the author’s name, the languages that the project supports, and any comments that you want to include. The General Information view is also where you configure general product information such as the product name, the product code (GUID), and the version number. In the same section, you can configure the application’s settings in Add/Remove Programs.
Adding Files and Folders to your Windows Installer
The main purpose of most installations is to transfer files from the source medium to the target destination. With InstallShield, adding files to your project is a simple drag-and-drop process in the Files and Folders view. This view contains a files explorer that enables you to drag and drop files from folders on your source machine to folders on the destination machine. The two left panes in the files explorer contain folders, and the two right panes display the files that are located within those folders. For more details, refer to the Files and Folders View in user guide.
Configure Prerequisites for your Windows Installer
More often than not, you have several dependencies of your application and wouldn’t want your users go through the process of figuring them out. A most common example could be the need of a specific .NET framework or a Java Runtime for your application to run. InstallShield allows you to configure what’s called prerequisites to install before your application installs so that both install time and runtime dependencies are resolved when the actual app is run. You can leverage the out-of-the-box prerequisites that are included with InstallShield or use the InstallShield Prerequisite Editor to create/configure your own. For more details, refer to the Prerequisites View in user guide.
Create and Configure Shortcuts
Every installation changes the target system in some way. The simplest installations might only copy files. More in-depth installations make registry changes, edit .ini files, or create shortcuts. InstallShield provides the separate views for making advanced configurations. Shortcuts offer quick access to your installed application. You can create shortcuts and program folders on the desktop, the Start menu, and various other locations.
The Shortcuts View provides a simple, visual way to create shortcuts to your application on the target system. This view contains a Shortcuts explorer that shows a set of predefined destination folders under which you can create shortcuts and subfolders. You can configure various settings for your shortcut like which icon to be used for shortcut, where to place the shortcut during installation etc.
Adding multiple languages to your Windows Installer package
InstallShield supports many features that enable you to customize your installer for global distribution. Using these features, you can create a single installation project that displays end-user text in multiple languages and can handle conditional installation of language-specific files. Creating a multilingual installation primarily involves separating code from language-specific resources and files. You may also need to distribute separate files for your installation, such as graphics, license files, or custom actions, depending on the language in which the installation is running. Another consideration is whether you need to install different application files depending on the target system’s locale. For more details, refer to the Creating Multilingual Installations in the user guide.
Digitally Sign your Windows Installer package
One of the last few steps that you’d like to do before distributing the package is to digitally sign your installer to avoid impersonation and allowing your users to trust your package. The Signing tab is where you specify the digital signature information—including the digital certificate files that a certification authority grated to you—that InstallShield should use to sign your files. It is also where you specify which files in your installation should be digitally signed at build time.
Integration with Visual Studio
If you are a developer who uses Visual Studio, InstallShield makes it increasingly convenient to create/edit/build windows installers right from within Visual Studio. The out of the box integration with Visual Studio allows developers to add project output to InstallShield projects without having to navigate away from Visual Studio. This integration simplifies the process of creating installation packages for Windows applications and streamlines the software development workflow. For more details, please refer to Integrating with Microsoft Visual Studio article.
Build MSIX Packages with InstallShield
MSIX is a introduced by Microsoft in 2018 as the next gen packaging format for distributing Windows applications. It is a successor to the earlier MSI (Microsoft Installer) format and provides several advantages over it. MSIX is designed to be secure, reliable, and flexible, with features that support both traditional and modern Windows applications. One of the key benefits of MSIX is that it provides a standardized and consistent way to package applications, making it easier to manage and deploy them across different Windows versions and devices. MSIX is the first installer format that can help with really clean uninstalls – leaving zero residue in the machine, once the package is removed. MSIX packages are self-contained and can include all necessary files, dependencies, and registry settings, reducing the risk of conflicts or errors during installation. MSIX also includes several security features, such as digital signing, file and registry virtualization, and runtime isolation, which help prevent unauthorized modifications or access to system resources by malicious or poorly designed applications.
InstallShield allows you to build MSIX packages in two ways
- If you already using InstallShield and building a windows installer using Basic MSI project, you can use the Appx/MSIX tab in releases view to build an MSIX package right away
- If you are starting from scratch, you can use the MSIX Project and get started
Here is a short video illustrating how you can create an MSIX package from scratch in simple steps:
Build your installers from within Azure DevOps pipelines
InstallShield can be integrated with Azure DevOps and you will be able to build your windows installers or any format directly in the pipelines. You can leverage either the hosted agents provisioned by Microsoft or configure your own private agent to build windows installers configured via InstallShield projects.
InstallShield uses a proprietary licensing model – Cloud License Server to simplify the process of building windows installers in hosted agents. Here is a short video on how to configure and build your installers in Azure DevOps pipelines