Установить программу с помощью powershell

Коллеги, привет) Меня зовут Юрий, и я IT-инженер сервиса 42Clouds. На поддержке у меня большое количество серверов, в том числе с ролью сервера предприятия по технологии 1С fresh. Довольно часто обновление конфигурации 1С требует повышения версии платформы 1С. Обновление вручную достаточно трудоемкий процесс и в связи с этим появилась идея автоматизации и упрощения этой задачи.

В этой статье я делюсь своим опытом и наработками по части автоматической установки 1С (будь то клиент, сервер или все вместе взятое).

Все решения, которые есть, меня не устраивали либо своим функционалом, либо требовали установки дополнительных компонентов, порой сторонних. Пришел к выводу, что проще сделать самостоятельно.

Собственно, что я хочу. Хочу указать в некотором текстовом файле (servers.txt) имена целевых серверов, и на них скриптом поставить нужные мне компоненты новой платформы со всеми необходимыми настройками.

Инструмент для автоматизации был выбран PowerShell. Сразу отмечу, что тестировалась работа скрипта лишь на Windows 2016, удаления предыдущих версий не включались в скрипт, но в дальнейшем доработаю и это.

How to Install Appx/EAppx or AppxBundle Windows 10 Apps using Powershell

  • как приложение, но тогда службу придется устанавливать вручную скриптом;
  • как сервис, при этом служба установится автоматически.

Скрипт устанавливает сервер предприятия (в дальнейшем СП) как приложение. Поэтому, если вы предыдущую версию платформы поставили вручную, а теперь новую версию будете ставить скриптом, учтите, что при удалении старой версии, удалится и служба 1С. Перед работой рекомендую удалить предыдущую версию СП.

А теперь сам скрипт (сразу отмечу, что с его помощью устанавливаю и клиента x32, и клиента x64, и СП):

#Список серверов для установки $Servers = Get-Content «.servers.txt» $Version = «8.3.20.1674»

#Источник дистрибутивов:

$SourcePath_x64 = «\192.168.0.100Install1CDistr»+$Version+»-64″
$SourcePath_x32 = «\192.168.0.100Install1CDistr»+$Version+»-32″

#Подготовительный этап: создание директории Temp_Install на каждом целевом сервере.

#Вспомогательные переменные

Источник: 42clouds.com

Install Software in PowerShell

Install Software in PowerShell

  1. Install Software in PowerShell
  2. Install Software Using the Start-Process Cmdlet in PowerShell
  3. Install Software Silently in PowerShell

PowerShell scripting language automates multiple Windows operating system tasks and processes. For example, PowerShell can execute various files like installation files with format MSI or .exe.

Читайте также:
Утилита это базовая система ввода вывода сервисная программа

Как установить приложения с помощью Powershell

кармический партне.

Please enable JavaScript

This article will demonstrate several methods and approaches to installing Windows PowerShell software.

Install Software in PowerShell

The following are the steps to install software using PowerShell:

Open your Windows PowerShell terminal.
Find the location of the .exe file and change the working directory to this.
Then, use the change directory or cd command to change the current working directory of the console.
Once we have adjusted our working directory, we may run our executable file by calling it to the command line.

.installer_setup.exe;

However, this method’s caveat would be that it will not suffice if we want to pass specific arguments when installing. Before, we had a legacy command called msiexec executed in the command prompt.

The following section will teach us the similar counterpart to msiexec in Windows PowerShell.

Install Software Using the Start-Process Cmdlet in PowerShell

The Start-Process command can run executable files in Windows PowerShell. The PowerShell cmdlet stated above and the -FilePath parameter takes the complete path of the .exe installation file.

Moreover, the -ArgumentList parameter provides the internal parameters used by the executable file when the installation process starts in Windows PowerShell. Lastly, the -PassThru parameter is used to verify that the command worked as we intended.

Suppose we want to open an executable file named installer_setup.exe .

Start-Process -Wait -FilePath ‘.installer_setup.exe’ -ArgumentList ‘/s’ -PassThru

Once the above script is executed, Windows PowerShell will run the defined executable file.

Install Software Silently in PowerShell

Running installation software in Windows PowerShell takes advantage of the msiexec legacy command that we usually use to run installation software in the command prompt.

To execute the installation software silently, we must use specific msiexec command parameters and pass them to the -ArgumentList parameter in Windows PowerShell.

  • /s : runs the installation in silent mode.
  • /v : passes command-line values and public properties options through the Msiexec.exe facility.
  • /q : sets user interface level.
  • n : interface level of the /q parameter; will run the installation with no graphical user interface.
Читайте также:
Goldwave как пользоваться программой

Combining all of the parameters above in one command is how the PowerShell script should look.

Start-Process -Wait -FilePath ‘.setup.exe’ -ArgumentList ‘/s /v/qn’ -PassThru

The installation should run in silent mode with no window or wizard prompts by executing the code snippet above.

It is worth noting that both the /v and /qn parameters are executed with no spaces between them because the /qn parameter is executed as a subfunction of the /v parameter.

The above parameters are not the only existing parameters under the msiexec command. You may run the msiexec command in PowerShell for more info.

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

Источник: www.delftstack.com

Как установить.MSI с помощью PowerShell

Я очень плохо знаком с PowerShell и испытываю трудности с пониманием.
Я хочу установить .MSI внутри скрипта PowerShell.
Пожалуйста, объясните мне, как это сделать, или предоставьте учебник для начинающих.

$wiObject = New-Object -ComObject WindowsInstaller.Installer .
user1719369 24 июл ’13 в 05:07 2013-07-24 05:07
2013-07-24 05:07

7 ответов

При попытке установить MSI без вывода сообщений через PowerShell с помощью этой команды:

Start-Process $webDeployInstallerFilePath -ArgumentList ‘/quiet’ -Wait

Я получаю ошибку:

Указанный исполняемый файл не является допустимым приложением для этой платформы ОС.

Я вместо этого переключился на использование msiexec.exe выполнить MSI с этой командой, и она работала как ожидалось:

$arguments = «/i `»$webDeployInstallerFilePath`» /quiet» Start-Process msiexec.exe -ArgumentList $arguments -Wait

Надеюсь, другие найдут это полезным.

user602585 14 май ’18 в 23:11 2018-05-14 23:11
2018-05-14 23:11

Зачем так увлекаться этим? Просто вызовите MSI-файл:

c:package.msi»

Вы также можете добавить еще несколько дополнительных параметров. Существуют общие параметры MSI и параметры, которые являются специфическими для вашего установщика. Для общих параметров просто позвоните msiexec

user978511 24 июл ’13 в 08:02 2013-07-24 08:02
2013-07-24 08:02

#Variables $computername = Get-Content ‘M:ApplicationsPowershellcomp listTest.txt’ $sourcefile = «\serverAppsLanSchool 7.7WindowsStudent.msi» #This section will install the software foreach ($computer in $computername) < $destinationFolder = «\$computerC$downloadLanSchool» #This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it. if (!(Test-Path -path $destinationFolder)) < New-Item $destinationFolder -Type Directory >Copy-Item -Path $sourcefile -Destination $destinationFolder Invoke-Command -ComputerName $computer -ScriptBlock < msiexec.exe /i c:downloadLanSchoolStudent.msi» /qn ADVANCED_OPTIONS=1 CHANNEL=100>>

Читайте также:
Инструкция для администратора программы

Я искал повсюду это сам и придумал пшик, но, наконец, совместил этот рабочий сценарий. Работает отлично! Мысль, которую я опубликую здесь, надеюсь, кому-то еще будет полезна Он вытягивает список компьютеров, копирует файлы на локальные машины и запускает его.:) время вечеринок!

user2992966 20 ноя ’13 в 18:43 2013-11-20 18:43
2013-11-20 18:43

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

так ваша команда будет выглядеть (например)

msiexec /i $_msiFiles /passive >
user3854483 16 фев ’15 в 03:11 2015-02-16 03:11
2015-02-16 03:11

В PowerShell 5.1 вы действительно можете использовать install-package, но он не может принимать дополнительные аргументы msi.

install-package .file.msi

В противном случае с запуском и ожиданием:

start -wait file.msi ALLUSERS=1,INSTALLDIR=C:FILE
user6654942 25 авг ’20 в 22:21 2020-08-25 22:21
2020-08-25 22:21
#$computerList = «Server Name» #$regVar = «Name of the package » #$packageName = «Packe name » $computerList = $args[0] $regVar = $args[1] $packageName = $args[2] foreach ($computer in $computerList) < Write-Host «Connecting to $computer. » Invoke-Command -ComputerName $computer -Authentication Kerberos -ScriptBlock < param( $computer, $regVar, $packageName ) Write-Host «Connected to $computer» if ([IntPtr]::Size -eq 4) < $registryLocation = Get-ChildItem «HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall» Write-Host «Connected to 32bit Architecture» >else < $registryLocation = Get-ChildItem «HKLM:SoftwareWow6432NodeMicrosoftWindowsCurrentVersionUninstall» Write-Host «Connected to 64bit Architecture» >Write-Host «Finding previous version of `enter code here`$regVar. » foreach ($registryItem in $registryLocation) < if((Get-itemproperty $registryItem.PSPath).DisplayName -match $regVar) < Write-Host «Found $regVar» (Get-itemproperty $registryItem.PSPath).DisplayName $UninstallString = (Get-itemproperty $registryItem.PSPath).UninstallString $match = [RegEx]::Match($uninstallString, «<.*?>») $args = «/x $($match.Value) /qb» Write-Host «Uninstalling $regVar. » [diagnostics.process]::start(«msiexec», $args).WaitForExit() Write-Host «Uninstalled $regVar» > > $path = «\$computerMsi$packageName» Write-Host «Installaing $path. » $args = » /i $path /qb» [diagnostics.process]::start(«msiexec», $args).WaitForExit() Write-Host «Installed $path» > -ArgumentList $computer, $regVar, $packageName Write-Host «Deployment Complete» >

Источник: stackru.com

Рейтинг
( Пока оценок нет )
Загрузка ...
EFT-Soft.ru