-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstall-RemoteMsi.ps1
More file actions
525 lines (453 loc) · 18.5 KB
/
Install-RemoteMsi.ps1
File metadata and controls
525 lines (453 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<#
.SYNOPSIS
Deploys .msi installers to remote Windows machines via PowerShell remoting.
.DESCRIPTION
This script copies an .msi installer from a network share to a remote machine
and executes it using msiexec.exe with silent installation arguments specified
in a JSON config file.
.PARAMETER ComputerName
The target computer name or IP address.
.PARAMETER Config
Path to a JSON configuration file specifying the installer details.
.PARAMETER Help
Display help information.
.EXAMPLE
.\Install-RemoteMsi.ps1 -ComputerName SERVER01 -Config .\configs\office-msi.json
.NOTES
Requires: PowerShell 5.1, Administrator privileges, WinRM enabled on target
#>
#Requires -Version 5.1
param(
[Parameter(Mandatory = $false)]
[string]$ComputerName,
[Parameter(Mandatory = $false)]
[string]$Config,
[Parameter(Mandatory = $false)]
[switch]$Help
)
#region Exit Codes
$Script:ExitCodes = @{
Success = 0
NotAdmin = 1
TargetUnreachable = 10
DnsResolutionFailed = 11
WinRMUnavailable = 12
RemoteSessionFailed = 13
TempDirectoryFailed = 20
SourceFileNotFound = 21
FileCopyFailed = 22
FileCopyVerifyFailed = 23
ConfigNotFound = 30
ConfigInvalid = 31
UnexpectedError = 99
InstallerOffset = 100
}
#endregion
#region Configuration
$Script:LoadedConfig = $null
#endregion
#region Functions
function Show-Help {
$configInfo = ""
if ($Script:LoadedConfig) {
$configInfo = @"
Loaded Configuration:
Display Name: $($Script:LoadedConfig.DisplayName)
Installer: $($Script:LoadedConfig.InstallerFilename)
Network Share: $($Script:LoadedConfig.NetworkSharePath)
Install Path: $($Script:LoadedConfig.InstallPath)
"@
}
Write-Host ""
Write-Host " Install-RemoteMsi.ps1" -ForegroundColor Cyan
Write-Host " Remote .msi installer deployment script" -ForegroundColor Gray
Write-Host ""
Write-Host " USAGE:" -ForegroundColor Yellow
Write-Host " .\Install-RemoteMsi.ps1 -ComputerName <target> -Config <path>"
Write-Host ""
Write-Host " PARAMETERS:" -ForegroundColor Yellow
Write-Host " -ComputerName Target computer name or IP address"
Write-Host " -Config Path to JSON configuration file"
Write-Host " -Help Display this help information"
Write-Host ""
Write-Host " EXAMPLES:" -ForegroundColor Yellow
Write-Host " .\Install-RemoteMsi.ps1 -ComputerName SERVER01 -Config .\configs\office-msi.json"
Write-Host " .\Install-RemoteMsi.ps1 -Help"
Write-Host ""
Write-Host " EXIT CODES:" -ForegroundColor Yellow
Write-Host " 0 Success"
Write-Host " 1 Not run as Administrator"
Write-Host " 10 Target unreachable (ping failed)"
Write-Host " 11 DNS resolution failed"
Write-Host " 12 WinRM unavailable"
Write-Host " 13 Remote session failed"
Write-Host " 20 Failed to create temp directory"
Write-Host " 21 Source file not found"
Write-Host " 22 File copy failed"
Write-Host " 23 File copy verification failed"
Write-Host " 30 Config file not found"
Write-Host " 31 Config file invalid"
Write-Host " 99 Unexpected error"
Write-Host " 100+ MSI exit codes (offset by 100)"
Write-Host ""
Write-Host " COMMON MSI EXIT CODES:" -ForegroundColor Yellow
Write-Host " 0 Success"
Write-Host " 1641 Success, reboot initiated"
Write-Host " 3010 Success, reboot required"
Write-Host " 1602 User cancelled installation"
Write-Host " 1603 Fatal error during installation"
if ($configInfo) {
Write-Host $configInfo -ForegroundColor Gray
}
Write-Host ""
}
function Import-InstallerConfig {
param([string]$ConfigPath)
if (-not (Test-Path $ConfigPath)) {
Write-Host "ERROR: Config file not found: $ConfigPath" -ForegroundColor Red
return $null
}
try {
$configContent = Get-Content $ConfigPath -Raw
$config = $configContent | ConvertFrom-Json
# Validate required fields
$requiredFields = @('DisplayName', 'NetworkSharePath', 'InstallerFilename', 'RemoteTempPath', 'InstallPath', 'SilentArgs', 'VerifyPath', 'ExitCodes')
foreach ($field in $requiredFields) {
if (-not $config.PSObject.Properties.Name.Contains($field)) {
Write-Host "ERROR: Config missing required field: $field" -ForegroundColor Red
return $null
}
}
# Process SilentArgs template - replace {{InstallPath}} placeholder
$config.SilentArgs = $config.SilentArgs -replace '\{\{InstallPath\}\}', $config.InstallPath
return $config
}
catch {
Write-Host "ERROR: Invalid config file: $($_.Exception.Message)" -ForegroundColor Red
return $null
}
}
function Test-TargetConnectivity {
param([string]$Target)
Write-Host " Checking connectivity to $Target..." -ForegroundColor Gray
# DNS Resolution
Write-Host " DNS resolution... " -NoNewline
try {
$dnsResult = [System.Net.Dns]::GetHostAddresses($Target)
if ($dnsResult.Count -eq 0) {
Write-Host "FAILED" -ForegroundColor Red
return $Script:ExitCodes.DnsResolutionFailed
}
Write-Host "OK ($($dnsResult[0].IPAddressToString))" -ForegroundColor Green
}
catch {
Write-Host "FAILED" -ForegroundColor Red
Write-Host " Could not resolve hostname: $Target" -ForegroundColor Red
return $Script:ExitCodes.DnsResolutionFailed
}
# Ping Test
Write-Host " Ping test... " -NoNewline
try {
$pingResult = Test-Connection -ComputerName $Target -Count 1 -Quiet -ErrorAction Stop
if (-not $pingResult) {
Write-Host "FAILED" -ForegroundColor Red
Write-Host " Target is not responding to ping" -ForegroundColor Red
return $Script:ExitCodes.TargetUnreachable
}
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "FAILED" -ForegroundColor Red
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return $Script:ExitCodes.TargetUnreachable
}
# WinRM Test
Write-Host " WinRM availability... " -NoNewline
try {
$wsmanResult = Test-WSMan -ComputerName $Target -ErrorAction Stop
if (-not $wsmanResult) {
Write-Host "FAILED" -ForegroundColor Red
return $Script:ExitCodes.WinRMUnavailable
}
Write-Host "OK" -ForegroundColor Green
}
catch {
Write-Host "FAILED" -ForegroundColor Red
Write-Host " WinRM is not available on $Target" -ForegroundColor Red
Write-Host " Run: Enable-PSRemoting -Force" -ForegroundColor Yellow
return $Script:ExitCodes.WinRMUnavailable
}
return $Script:ExitCodes.Success
}
function Copy-InstallerToRemote {
param(
[string]$Target,
[string]$SourcePath,
[string]$RemoteTempPath
)
# Verify source file exists
Write-Host " Verifying source file..." -ForegroundColor Gray
Write-Host " Source: $SourcePath" -ForegroundColor Gray
if (-not (Test-Path $SourcePath)) {
Write-Host " ERROR: Source file not found" -ForegroundColor Red
return $Script:ExitCodes.SourceFileNotFound
}
Write-Host " Source file exists" -ForegroundColor Green
# Create remote temp directory via admin share
$remoteTempUNC = "\\$Target\$($RemoteTempPath.Replace(':', '$'))"
Write-Host " Creating remote temp directory..." -ForegroundColor Gray
Write-Host " Path: $remoteTempUNC" -ForegroundColor Gray
try {
if (-not (Test-Path $remoteTempUNC)) {
New-Item -Path $remoteTempUNC -ItemType Directory -Force | Out-Null
}
Write-Host " Directory ready" -ForegroundColor Green
}
catch {
Write-Host " ERROR: Failed to create directory" -ForegroundColor Red
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return $Script:ExitCodes.TempDirectoryFailed
}
# Copy installer file
$installerName = Split-Path $SourcePath -Leaf
$remoteFilePath = Join-Path $remoteTempUNC $installerName
Write-Host " Copying installer to remote machine..." -ForegroundColor Gray
Write-Host " Destination: $remoteFilePath" -ForegroundColor Gray
try {
Copy-Item -Path $SourcePath -Destination $remoteFilePath -Force -ErrorAction Stop
Write-Host " Copy completed" -ForegroundColor Green
}
catch {
Write-Host " ERROR: Copy failed" -ForegroundColor Red
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return $Script:ExitCodes.FileCopyFailed
}
# Verify copy
Write-Host " Verifying copy..." -ForegroundColor Gray
if (-not (Test-Path $remoteFilePath)) {
Write-Host " ERROR: File verification failed" -ForegroundColor Red
return $Script:ExitCodes.FileCopyVerifyFailed
}
$sourceSize = (Get-Item $SourcePath).Length
$remoteSize = (Get-Item $remoteFilePath).Length
if ($sourceSize -ne $remoteSize) {
Write-Host " ERROR: File size mismatch (source: $sourceSize, remote: $remoteSize)" -ForegroundColor Red
return $Script:ExitCodes.FileCopyVerifyFailed
}
Write-Host " Verification passed" -ForegroundColor Green
return $Script:ExitCodes.Success
}
function Invoke-RemoteInstall {
param(
[string]$Target,
[object]$Config
)
$installerPath = Join-Path $Config.RemoteTempPath $Config.InstallerFilename
$silentArgs = $Config.SilentArgs
$installPath = $Config.InstallPath
$verifyPath = $Config.VerifyPath
$remoteScriptBlock = {
param($InstallerPath, $SilentArgs, $InstallPath, $VerifyPath)
$result = @{
ExitCode = 0
Message = ""
Verified = $false
}
try {
# Run the MSI installer via msiexec.exe
$msiArgs = "/i `"$InstallerPath`" $SilentArgs"
$process = Start-Process -FilePath "msiexec.exe" -ArgumentList $msiArgs -Wait -PassThru -WindowStyle Hidden
$result.ExitCode = $process.ExitCode
# MSI success codes: 0 (success), 1641 (reboot initiated), 3010 (reboot required)
$successCodes = @(0, 1641, 3010)
if ($successCodes -contains $process.ExitCode) {
# Verify installation
$fullVerifyPath = Join-Path $InstallPath $VerifyPath
if (Test-Path $fullVerifyPath) {
$result.Verified = $true
$result.Message = "Installation verified successfully"
}
else {
$result.Message = "Installation completed but verification failed - $VerifyPath not found"
}
}
else {
$result.Message = "MSI installer exited with code $($process.ExitCode)"
}
}
catch {
$result.ExitCode = 99
$result.Message = "Exception during installation: $($_.Exception.Message)"
}
return $result
}
Write-Host " Executing remote MSI installation..." -ForegroundColor Gray
Write-Host " Installer: $installerPath" -ForegroundColor Gray
Write-Host " msiexec args: /i `"$installerPath`" $silentArgs" -ForegroundColor Gray
try {
$session = New-PSSession -ComputerName $Target -ErrorAction Stop
}
catch {
Write-Host " ERROR: Failed to create remote session" -ForegroundColor Red
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return @{ ExitCode = $Script:ExitCodes.RemoteSessionFailed; Message = "Remote session failed"; Verified = $false }
}
try {
$result = Invoke-Command -Session $session -ScriptBlock $remoteScriptBlock -ArgumentList $installerPath, $silentArgs, $installPath, $verifyPath
return $result
}
catch {
Write-Host " ERROR: Remote execution failed" -ForegroundColor Red
Write-Host " $($_.Exception.Message)" -ForegroundColor Red
return @{ ExitCode = $Script:ExitCodes.UnexpectedError; Message = "Remote execution failed"; Verified = $false }
}
finally {
Remove-PSSession -Session $session -ErrorAction SilentlyContinue
}
}
function Get-ExitCodeMessage {
param(
[int]$ExitCode,
[object]$Config
)
$codeString = $ExitCode.ToString()
if ($Config.ExitCodes.PSObject.Properties.Name.Contains($codeString)) {
return $Config.ExitCodes.$codeString
}
return "Unknown exit code"
}
function Remove-RemoteInstaller {
param(
[string]$Target,
[string]$RemoteTempPath,
[string]$InstallerFilename
)
Write-Host "Cleanup:" -ForegroundColor Yellow
Write-Host " Removing installer from remote temp..." -ForegroundColor Gray
$remoteTempUNC = "\\$Target\$($RemoteTempPath.Replace(':', '$'))"
$remoteFilePath = Join-Path $remoteTempUNC $InstallerFilename
try {
if (Test-Path $remoteFilePath) {
Remove-Item -Path $remoteFilePath -Force -ErrorAction Stop
Write-Host " Installer removed" -ForegroundColor Green
}
else {
Write-Host " Installer not found (already removed)" -ForegroundColor Gray
}
}
catch {
Write-Host " WARNING: Failed to remove installer" -ForegroundColor Yellow
Write-Host " $($_.Exception.Message)" -ForegroundColor Yellow
}
Write-Host ""
}
#endregion
#region Main Execution
# Handle help request first
if ($Help) {
if ($Config -and (Test-Path $Config)) {
$Script:LoadedConfig = Import-InstallerConfig -ConfigPath $Config
}
Show-Help
exit $Script:ExitCodes.Success
}
# Check for Administrator privileges
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host ""
Write-Host "ERROR: This script requires Administrator privileges" -ForegroundColor Red
Write-Host "Please run PowerShell as Administrator and try again" -ForegroundColor Yellow
Write-Host ""
exit $Script:ExitCodes.NotAdmin
}
# Validate required parameters
if (-not $ComputerName -or -not $Config) {
Write-Host ""
Write-Host "ERROR: Missing required parameters" -ForegroundColor Red
Write-Host "Usage: .\Install-RemoteMsi.ps1 -ComputerName <target> -Config <path>" -ForegroundColor Yellow
Write-Host "Run with -Help for more information" -ForegroundColor Yellow
Write-Host ""
exit $Script:ExitCodes.ConfigNotFound
}
# Load configuration
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Remote MSI Installer" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Loading configuration..." -ForegroundColor Gray
$Script:LoadedConfig = Import-InstallerConfig -ConfigPath $Config
if (-not $Script:LoadedConfig) {
exit $Script:ExitCodes.ConfigInvalid
}
Write-Host " Loaded: $($Script:LoadedConfig.DisplayName)" -ForegroundColor Green
Write-Host ""
# Display installation info
Write-Host "Installation Details:" -ForegroundColor Yellow
Write-Host " Target: $ComputerName" -ForegroundColor Gray
Write-Host " Software: $($Script:LoadedConfig.DisplayName)" -ForegroundColor Gray
Write-Host " Installer: $($Script:LoadedConfig.InstallerFilename)" -ForegroundColor Gray
Write-Host " Install Path: $($Script:LoadedConfig.InstallPath)" -ForegroundColor Gray
Write-Host ""
# Pre-flight checks
Write-Host "Pre-flight Checks:" -ForegroundColor Yellow
$connectivityResult = Test-TargetConnectivity -Target $ComputerName
if ($connectivityResult -ne $Script:ExitCodes.Success) {
Write-Host ""
Write-Host "Pre-flight checks failed. Aborting." -ForegroundColor Red
exit $connectivityResult
}
Write-Host ""
# Copy installer
Write-Host "File Transfer:" -ForegroundColor Yellow
$sourcePath = Join-Path $Script:LoadedConfig.NetworkSharePath $Script:LoadedConfig.InstallerFilename
$copyResult = Copy-InstallerToRemote -Target $ComputerName -SourcePath $sourcePath -RemoteTempPath $Script:LoadedConfig.RemoteTempPath
if ($copyResult -ne $Script:ExitCodes.Success) {
Write-Host ""
Write-Host "File transfer failed. Aborting." -ForegroundColor Red
exit $copyResult
}
Write-Host ""
# Execute installation
Write-Host "Installation:" -ForegroundColor Yellow
$installResult = Invoke-RemoteInstall -Target $ComputerName -Config $Script:LoadedConfig
Write-Host ""
# Cleanup installer from remote temp
Remove-RemoteInstaller -Target $ComputerName -RemoteTempPath $Script:LoadedConfig.RemoteTempPath -InstallerFilename $Script:LoadedConfig.InstallerFilename
# Report results
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " Installation Result" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
$exitCodeMessage = Get-ExitCodeMessage -ExitCode $installResult.ExitCode -Config $Script:LoadedConfig
# MSI success codes: 0 (success), 1641 (reboot initiated), 3010 (reboot required)
$successCodes = @(0, 1641, 3010)
if ($successCodes -contains $installResult.ExitCode) {
if ($installResult.Verified) {
Write-Host " Status: SUCCESS" -ForegroundColor Green
Write-Host " Verified: Yes" -ForegroundColor Green
}
else {
Write-Host " Status: SUCCESS (unverified)" -ForegroundColor Yellow
Write-Host " Verified: No" -ForegroundColor Yellow
Write-Host " Message: $($installResult.Message)" -ForegroundColor Yellow
}
if ($installResult.ExitCode -eq 1641) {
Write-Host " Note: Reboot has been initiated" -ForegroundColor Yellow
}
elseif ($installResult.ExitCode -eq 3010) {
Write-Host " Note: Reboot required to complete installation" -ForegroundColor Yellow
}
Write-Host ""
exit $Script:ExitCodes.Success
}
else {
Write-Host " Status: FAILED" -ForegroundColor Red
Write-Host " Exit Code: $($installResult.ExitCode)" -ForegroundColor Red
Write-Host " Message: $exitCodeMessage" -ForegroundColor Red
Write-Host ""
# Return installer exit code offset by 100
$finalExitCode = $Script:ExitCodes.InstallerOffset + $installResult.ExitCode
exit $finalExitCode
}
#endregion