Windows powershell package manager

Работа с программами установки программного обеспечения Working with Software Installations

Доступ к приложениям, использующим установщик Windows, можно получить в классе Win32_Product WMI, но не все современные приложения используют установщик Windows. Applications that are designed to use Windows Installer can be accessed through WMI’s Win32_Product class, but not all applications in use today use the Windows Installer. Установщик Windows обычно не управляет приложениями, использующими другие процедуры установки. Applications that use alternate setup routines are not usually managed by the Windows Installer. Конкретные техники работы с этими приложениями зависят от программного обеспечения установщика и решений, принятых разработчиком приложения. Specific techniques for working with those applications depends on the installer software and decisions made by the application developer. Например, для управления приложениями, установленными путем копирования файлов в папку на компьютере, обычно не используются описанные здесь методы. For example, applications installed by copying the files to a folder on the computer usually cannot be managed by using techniques discussed here. Вы можете управлять этими приложениями, как файлами и папками, с помощью способов, приведенных в статье Работа с файлами и папками. You can manage these applications as files and folders by using the techniques discussed in Working With Files and Folders.

Класс Win32_Product не оптимизирован для запросов. The Win32_Product class is not query optimized. Если выполняются запросы, использующие фильтры с подстановочными знаками, то WMI будет использовать поставщика MSI для перечисления всех установленных продуктов, а затем последовательно проанализирует весь список с применением фильтра. Queries that use wildcard filters cause WMI to use the MSI provider to enumerate all installed products then parse the full list sequentially to handle the filter. При этом также инициируется проверка согласованности установленных пакетов для проверки и исправления установки. This also initiates a consistency check of packages installed, verifying and repairing the install. Проверка выполняется медленно и может привести к ошибкам в журнале событий. The validation is a slow process and may result in errors in the event logs. Подробные сведения см. в статье базы знаний 974524. For more information seek KB article 974524.

Создание списков приложений установщика Windows Listing Windows Installer Applications

Чтобы создать список приложений, установленных с помощью установщика Windows в локальной или удаленной системе, используйте следующий простой запрос WMI: To list the applications installed with the Windows Installer on a local or remote system, use the following simple WMI query:

Чтобы отобразить все свойства объекта Win32_Product , используйте параметр Properties командлетов форматирования, например Format-List со значением * (все). To display all the properties of the Win32_Product object to the display, use the Properties parameter of the formatting cmdlets, such as the Format-List cmdlet, with a value of * (all).

Можно также использовать параметр Get-CimInstance Filter , чтобы выбрать только среду выполнения Microsoft .NET 2.0. Or, you could use the Get-CimInstance Filter parameter to select only Microsoft .NET 2.0 Runtime. Для значения параметра Filter используется синтаксис языка запросов WMI (WQL), а не синтаксис Windows PowerShell. The value of the Filter parameter uses WMI Query Language (WQL) syntax, not Windows PowerShell syntax. Пример: For example:

Читайте также:  Lenovo vantage для windows 10 64 bit

Чтобы получить список только интересующих вас свойств, используйте параметр Property командлетов форматирования. To list only the properties that interest you, use the Property parameter of the formatting cmdlets to list the desired properties.

Создание списка всех удаленных приложений Listing All Uninstallable Applications

Так как большинство стандартных приложений регистрируют программу удаления в Windows, с ними можно работать локально, в реестре Windows. Because most standard applications register an uninstaller with Windows, we can work with those locally by finding them in the Windows registry. Не существует гарантированного способа найти все приложения в системе. There is no guaranteed way to find every application on a system. Но можно найти все программы в списках, отображаемых в окне Установка и удаление программ в следующем разделе реестра: However, it is possible to find all programs with listings displayed in Add or Remove Programs in the following registry key:

В этом разделе можно найти приложения. We can examine this key to find applications. Чтобы упростить просмотр раздела Uninstall, можно сопоставить диск PowerShell с таким путем реестра: To make it easier to view the Uninstall key, we can map a PowerShell drive to this registry location:

Теперь диск с именем «Uninstall» можно использовать для быстрого и удобного поиска установок приложений. We now have a drive named «Uninstall:» that can be used to quickly and conveniently look for application installations. Количество установленных приложений можно найти, подсчитав количество разделов реестра в разделе «Удаление»: Диск PowerShell: We can find the number of installed applications by counting the number of registry keys in the Uninstall: PowerShell drive:

С помощью разных методов, начиная с Get-ChildItem , можно дальше выполнять поиск в списке приложений. We can search this list of applications further by using a variety of techniques, beginning with Get-ChildItem . Чтобы получить список приложений и сохранить их в переменную $UninstallableApplications , используйте следующую команду: To get a list of applications and save them in the $UninstallableApplications variable, use the following command:

Чтобы отобразить значения записей реестра в подразделах реестра раздела «Удаление», используйте метод GetValue. To display the values of the registry entries in the registry keys under Uninstall, use the GetValue method of the registry keys. Значение метода является записью реестра. The value of the method is the name of the registry entry.

Например, чтобы найти отображаемые имена приложений в разделе «Удаление», используйте следующую команду: For example, to find the display names of applications in the Uninstall key, use the following command:

Нет никакой гарантии, что эти значения уникальны. There is no guarantee that these values are unique. В следующем примере два установленных элемента отображаются как Windows Media Encoder 9 Series: In the following example, two installed items appear as «Windows Media Encoder 9 Series»:

Установка приложений Installing Applications

Вы можете использовать класс Win32_Product для удаленной или локальной установки пакетов установщика Windows. You can use the Win32_Product class to install Windows Installer packages, remotely or locally.

Чтобы установить приложение, запустите PowerShell, используя параметр «Запуск от имени администратора». To install an application, you must start PowerShell with the «Run as administrator» option.

Если установка выполняется удаленно, используйте сетевой UNC-путь, чтобы указать путь к пакету MSI, так как подсистема WMI не распознает пути PowerShell. When installing remotely, use a Universal Naming Convention (UNC) network path to specify the path to the .msi package, because the WMI subsystem does not understand PowerShell paths. Например, чтобы установить пакет NewPackage.msi, расположенный в сетевой папке \\AppServ\dsp на удаленном компьютере PC01, введите следующую команду в командной строке PowerShell: For example, to install the NewPackage.msi package located in the network share \\AppServ\dsp on the remote computer PC01, type the following command at the PowerShell prompt:

Читайте также:  Windows update removal tool

Приложения, которые не используют метод установщика Windows, могут включать специальные методы для автоматического развертывания конкретного приложения. Applications that do not use Windows Installer technology may have application-specific methods for automated deployment. Изучите документацию по приложению или обратитесь в службу поддержки поставщика приложения. Check the documentation for the application or consult the application vendor’s support system.

Удаление приложений Removing Applications

Удаление пакета установщика Windows с помощью PowerShell работает примерно так же, как и установка пакета. Removing a Windows Installer package using PowerShell works in approximately the same way as installing a package. Далее представлен пример, в котором пакет для удаления выбирается на основе имени. В некоторых случаях его может быть проще отфильтровать с помощью IdentifyingNumber : Here is an example that selects the package to uninstall based on its name; in some cases it may be easier to filter with the IdentifyingNumber :

Удаление других приложений не так просто, даже если оно выполняется локально. Removing other applications is not quite so simple, even when done locally. Строки удаления командной строки для этих приложений можно найти путем извлечения свойства UninstallString . We can find the command line uninstallation strings for these applications by extracting the UninstallString property. Этот способ работает для приложений установщика Windows и более старых программ, отображающихся в разделе «Удаление»: This method works for Windows Installer applications and for older programs appearing under the Uninstall key:

Выходные данные при необходимости можно отфильтровать по отображаемому имени: You can filter the output by the display name, if you like:

Возможно, что эти строки нельзя будет напрямую использовать из командной строки PowerShell без внесения некоторых изменений. However, these strings may not be directly usable from the PowerShell prompt without some modification.

Обновление приложений установщика Windows Upgrading Windows Installer Applications

Чтобы обновить приложение, необходимо знать название приложения и путь к пакету обновлений приложения. To upgrade an application, you need to know the name of the application and the path to the application upgrade package. Получив эти сведения, вы можете обновить приложение с помощью одной команды PowerShell: With that information, you can upgrade an application with a single PowerShell command:

Install-Package (консоль диспетчера пакетов в Visual Studio) Install-Package (Package Manager Console in Visual Studio)

В этом разделе описывается команда в консоли диспетчера пакетов в Visual Studio в Windows. Общие команды PowerShell Install-Package см. в справочнике по PackageManagement для PowerShell. This topic describes the command within the Package Manager Console in Visual Studio on Windows. For the generic PowerShell Install-Package command, see the PowerShell PackageManagement reference.

Устанавливает пакет и его зависимости в проект. Installs a package and its dependencies into a project.

Синтаксис Syntax

В NuGet 2.8 + Install-Package может понизить уровень существующего пакета в проекте. In NuGet 2.8+, Install-Package can downgrade an existing package in your project. Например, при наличии установленного Microsoft. AspNet. MVC 5.1.0-RC1 Следующая команда понизить ее до 5.0.0: For example, if you have Microsoft.AspNet.MVC 5.1.0-rc1 installed, the following command would downgrade it to 5.0.0:

Читайте также:  Убрать запрос пароля windows server

Параметры Parameters

Параметр Parameter Описание Description
Id Id Необходимости Идентификатор устанавливаемого пакета. (Required) The identifier of the package to install. (3.0 +) Идентификатор может быть путем или URL-адресом packages.config файла или .nupkg файла. (3.0+) The identifier can be a path or URL of a packages.config file or a .nupkg file. Сам переключатель-ID является необязательным. The -Id switch itself is optional.
игноредепенденЦиес IgnoreDependencies Установить только этот пакет, но не его зависимости. Install only this package and not its dependencies.
ProjectName ProjectName Проект, в который устанавливается пакет, по умолчанию используемый в качестве проекта по умолчанию. The project into which to install the package, defaulting to the default project.
Источник Source URL-адрес или путь к папке для источника пакета для поиска. The URL or folder path for the package source to search. Пути к локальным папкам могут быть абсолютными или относительно текущей папки. Local folder paths can be absolute, or relative to the current folder. Если этот параметр опущен, Install-Package Поиск выполняется в текущем выбранном источнике пакета. If omitted, Install-Package searches the currently selected package source.
Версия Version Версия устанавливаемого пакета, по умолчанию — последняя версия. The version of the package to install, defaulting to the latest version.
инклудепререлеасе IncludePrerelease Учитываются предварительные пакеты для установки. Considers prerelease packages for the install. Если пропущен, учитываются только стабильные версии пакетов. If omitted, only stable packages are considered.
филеконфликтактион FileConflictAction Действие, предпринимаемое при запросе перезаписи или пропуска существующих файлов, на которые ссылается проект. The action to take when asked to overwrite or ignore existing files referenced by the project. Возможные значения: overwrite, ignore, None, овервритеалл и (3.0 +)IgnoreAll. Possible values are Overwrite, Ignore, None, OverwriteAll, and (3.0+)IgnoreAll.
депенденциверсион DependencyVersion Используемая версия пакетов зависимостей, которая может быть одной из следующих: The version of the dependency packages to use, which can be one of the following:
  • Самый низкий (по умолчанию): самая низкая версия Lowest (default): the lowest version
  • Хигхестпатч: версия с наименьшим основным, наименьшим незначительным, самым высоким исправлением HighestPatch: the version with the lowest major, lowest minor, highest patch
  • Хигхестминор: версия с наименьшим основным, наибольшим незначительным, самым высоким исправлением HighestMinor: the version with the lowest major, highest minor, highest patch
  • Высший (по умолчанию для Update-Package без параметров): самая высокая версия Highest (default for Update-Package with no parameters): the highest version

Значение по умолчанию можно задать с помощью dependencyVersion параметра в Nuget.Config файле. You can set the default value using the dependencyVersion setting in the Nuget.Config file.

WhatIf WhatIf Показывает, что произойдет при выполнении команды без фактического выполнения установки. Shows what would happen when running the command without actually performing the install.

Ни один из этих параметров не принимает входные данные конвейера или подстановочные знаки. None of these parameters accept pipeline input or wildcard characters.

Общие параметры Common Parameters

Install-Package поддерживает следующие Общие параметры PowerShell: Отладка, действие при ошибке, ErrorVariable, буфер, переменная, PipelineVariable, Verbose, WarningAction и WarningVariable. Install-Package supports the following common PowerShell parameters: Debug, Error Action, ErrorVariable, OutBuffer, OutVariable, PipelineVariable, Verbose, WarningAction, and WarningVariable.

Оцените статью