-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathInstall.ps1
376 lines (342 loc) · 15.2 KB
/
Install.ps1
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
<#
.SYNOPSIS
Installs an application based on logic defined in Install.json. Simple alternative to PSAppDeployToolkit
Script is copied into Source folder if Install.json exists.
.NOTES
Author: Aaron Parker
Update: Constantin Lotz
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param ()
# Pass WhatIf and Verbose preferences to functions and cmdlets below
if ($WhatIfPreference -eq $true) { $Script:WhatIfPref = $true } else { $WhatIfPref = $false }
if ($VerbosePreference -eq $true) { $Script:VerbosePref = $true } else { $VerbosePref = $false }
#region Restart if running in a 32-bit session
if (!([System.Environment]::Is64BitProcess)) {
if ([System.Environment]::Is64BitOperatingSystem) {
# Create a string from the passed parameters
[System.String]$ParameterString = ""
foreach ($Parameter in $PSBoundParameters.GetEnumerator()) {
$ParameterString += " -$($Parameter.Key) $($Parameter.Value)"
}
# Execute the script in a 64-bit process with the passed parameters
$Arguments = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$($MyInvocation.MyCommand.Definition)`"$ParameterString"
$ProcessPath = $(Join-Path -Path $Env:SystemRoot -ChildPath "\Sysnative\WindowsPowerShell\v1.0\powershell.exe")
Write-LogFile -Message "Restarting in 64-bit PowerShell."
Write-LogFile -Message "File path: $ProcessPath."
Write-LogFile -Message "Arguments: $Arguments."
$params = @{
FilePath = $ProcessPath
ArgumentList = $Arguments
Wait = $True
WindowStyle = "Hidden"
}
Start-Process @params
exit 0
}
}
#endregion
#region Logging Function
function Write-LogFile {
<#
.SYNOPSIS
This function creates or appends a line to a log file
.DESCRIPTION
This function writes a log line to a log file in the form synonymous with
ConfigMgr logs so that tools such as CMtrace and SMStrace can easily parse
the log file. It uses the ConfigMgr client log format's file section
to add the line of the script in which it was called.
.PARAMETER Message
The message parameter is the log message you'd like to record to the log file
.PARAMETER LogLevel
The logging level is the severity rating for the message you're recording. Like ConfigMgr
clients, you have 3 severity levels available; 1, 2 and 3 from informational messages
for FYI to critical messages that stop the install. This defaults to 1.
.EXAMPLE
PS C:\> Write-LogFile -Message 'Value1' -LogLevel 'Value2'
This example shows how to call the Write-LogFile function with named parameters.
.NOTES
Constantin Lotz;
Adam Bertram, https://github.com/adbertram/PowerShellTipsToWriteBy/blob/f865c4212284dc25fe613ca70d9a4bafb6c7e0fe/chapter_7.ps1#L5
#>
[CmdletBinding(SupportsShouldProcess = $false)]
param (
[Parameter(Position = 0, ValueFromPipeline = $true, Mandatory = $true)]
[System.String] $Message,
[Parameter(Position = 1, Mandatory = $false)]
[ValidateSet(1, 2, 3)]
[System.Int16] $LogLevel = 1
)
process {
## Build the line which will be recorded to the log file
$TimeGenerated = "$(Get-Date -Format HH:mm:ss).$((Get-Date).Millisecond)+000"
$LineFormat = $Message, $TimeGenerated, (Get-Date -Format "yyyy-MM-dd"), "$($MyInvocation.ScriptName | Split-Path -Leaf):$($MyInvocation.ScriptLineNumber)", $LogLevel
$Line = '<![LOG[{0}]LOG]!><time="{1}" date="{2}" component="{3}" context="" type="{4}" thread="" file="">' -f $LineFormat
Write-Information -MessageData $Message -InformationAction "Continue"
Add-Content -Value $Line -Path $Script:LogFile
}
}
#endregion
#region Installer functions
function Get-InstallConfig {
param (
[System.String] $File = "Install.json",
[System.Management.Automation.PathInfo] $Path = $PWD
)
try {
$InstallFile = Join-Path -Path $Path -ChildPath $File
Write-LogFile -Message "Read package install config: $InstallFile"
Get-Content -Path $InstallFile -ErrorAction "Stop" | ConvertFrom-Json -ErrorAction "Continue"
}
catch {
Write-LogFile -Message "Get-InstallConfig: $($_.Exception.Message)" -LogLevel 3
throw $_
}
}
function Get-Installer {
param (
[System.String] $File,
[System.Management.Automation.PathInfo] $Path = $PWD
)
$Installer = Get-ChildItem -Path $Path -Filter $File -Recurse -ErrorAction "Continue" | Select-Object -First 1
if ([System.String]::IsNullOrEmpty($Installer.FullName)) {
Write-LogFile -Message "File not found: $File" -LogLevel 3
throw [System.IO.FileNotFoundException]::New("File not found: $File")
}
else {
Write-LogFile -Message "Found installer: $($Installer.FullName)"
return $Installer.FullName
}
}
function Copy-File {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[System.Array] $File,
[System.Management.Automation.PathInfo] $Path = $PWD
)
process {
foreach ($Item in $File) {
try {
$FilePath = Get-ChildItem -Path $Path -Filter $Item.Source -Recurse -ErrorAction "Continue"
Write-LogFile -Message "Copy-File: Source: $($FilePath.FullName)"
Write-LogFile -Message "Copy-File: Destination: $($Item.Destination)"
$params = @{
Path = $FilePath.FullName
Destination = $Item.Destination
Container = $false
Force = $true
ErrorAction = "Continue"
WhatIf = $Script:WhatIfPref
Verbose = $Script:VerbosePref
}
Copy-Item @params
}
catch {
Write-LogFile -Message "Copy-File: $($_.Exception.Message)" -LogLevel 3
Write-Warning -Message $_.Exception.Message
}
}
}
}
function Remove-Path {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[System.String[]] $Path
)
process {
foreach ($Item in $Path) {
try {
if (Test-Path -Path $Item -PathType "Container") {
$params = @{
Path = $Item
Recurse = $true
Force = $true
ErrorAction = "Continue"
WhatIf = $Script:WhatIfPref
Verbose = $Script:VerbosePref
}
Remove-Item @params
Write-LogFile -Message "Remove-Item: $Item"
}
else {
$params = @{
Path = $Item
Force = $true
ErrorAction = "Continue"
WhatIf = $Script:WhatIfPref
Verbose = $Script:VerbosePref
}
Remove-Item @params
Write-LogFile -Message "Remove-Item: $Item"
}
}
catch {
Write-LogFile -Message "Remove-Path error: $($_.Exception.Message)" -LogLevel 3
Write-Warning -Message $_.Exception.Message
}
}
}
}
function Stop-PathProcess {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[System.String[]] $Path,
[System.Management.Automation.SwitchParameter] $Force
)
process {
foreach ($Item in $Path) {
try {
Get-Process | Where-Object { $_.Path -like $Item } | ForEach-Object { Write-LogFile -Message "Stop-PathProcess: $($_.ProcessName)" }
$params = {
ErrorAction = "Continue"
WhatIf = $Script:WhatIfPref
Verbose = $Script:VerbosePref
}
if ($PSBoundParameters.ContainsKey("Force")) {
Get-Process | Where-Object { $_.Path -like $Item } | `
Stop-Process -Force @params
}
else {
Get-Process | Where-Object { $_.Path -like $Item } | `
Stop-Process @params
}
}
catch {
Write-LogFile -Message "Stop-PathProcess error: $($_.Exception.Message)" -LogLevel 2
Write-Warning -Message $_.Exception.Message
}
}
}
}
function Uninstall-Msi {
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[System.String[]] $ProductName,
[System.String] $LogPath
)
process {
foreach ($Item in $ProductName) {
if ($PSCmdlet.ShouldProcess($Item)) {
$Product = Get-CimInstance -Class "Win32_InstalledWin32Program" | Where-Object { $_.Name -like $Item }
try {
$Product = Get-CimInstance -Class "Win32_InstalledWin32Program" | Where-Object { $_.Name -like $Item }
$params = @{
FilePath = "$Env:SystemRoot\System32\msiexec.exe"
ArgumentList = "/uninstall `"$($Product.MsiProductCode)`" /quiet /log `"$LogPath\Uninstall-$($Item -replace " ").log`""
NoNewWindow = $true
PassThru = $true
Wait = $true
ErrorAction = "Continue"
Verbose = $Script:VerbosePref
}
$result = Start-Process @params
Write-LogFile -Message "$Env:SystemRoot\System32\msiexec.exe /uninstall `"$($Product.MsiProductCode)`" /quiet /log `"$LogPath\Uninstall-$($Item -replace " ").log`""
Write-LogFile -Message "Msiexec result: $($result.ExitCode)"
return $result.ExitCode
}
catch {
Write-LogFile -Message "Uninstall-Msi error: $($_.Exception.Message)" -LogLevel 3
Write-Warning -Message $_.Exception.Message
}
}
}
}
}
#endregion
#region Install logic
# Log file path. Parent directory should exist if device is enrolled in Intune
$Script:LogFile = "$Env:ProgramData\Microsoft\IntuneManagementExtension\Logs\PSPackageFactoryInstall.log"
# Trim log if greater than 50 MB
if (Test-Path -Path $Script:LogFile) {
if ((Get-Item -Path $Script:LogFile).Length -gt 50MB) {
Clear-Content -Path $Script:LogFile
Write-LogFile -Message "Log file size greater than 50MB. Clearing log." -LogLevel 2
}
}
# Get the install details for this application
$Install = Get-InstallConfig
$Installer = Get-Installer -File $Install.PackageInformation.SetupFile
if ([System.String]::IsNullOrEmpty($Installer)) {
Write-LogFile -Message "File not found: $($Install.PackageInformation.SetupFile)" -LogLevel 3
throw [System.IO.FileNotFoundException]::New("File not found: $($Install.PackageInformation.SetupFile)")
}
else {
# Stop processes before installing the application
if ($Install.InstallTasks.StopPath.Count -gt 0) { Stop-PathProcess -Path $Install.InstallTasks.StopPath }
# Uninstall the application
if ($Install.InstallTasks.UninstallMsi.Count -gt 0) { Uninstall-Msi -ProductName $Install.InstallTasks.UninstallMsi -LogPath $Install.LogPath }
if ($Install.InstallTasks.Remove.Count -gt 0) { Remove-Path -Path $Install.InstallTasks.Remove }
# Create the log folder
if (Test-Path -Path $Install.LogPath -PathType "Container") {
Write-LogFile -Message "Directory exists: $($Install.LogPath)"
}
else {
Write-LogFile -Message "Create directory: $($Install.LogPath)"
New-Item -Path $Install.LogPath -ItemType "Directory" -ErrorAction "Continue" | Out-Null
}
# Build the argument list
$ArgumentList = $Install.InstallTasks.ArgumentList -replace "#SetupFile", $Installer
$ArgumentList = $ArgumentList -replace "#LogName", $Install.PackageInformation.SetupFile
$ArgumentList = $ArgumentList -replace "#LogPath", $Install.LogPath
$ArgumentList = $ArgumentList -replace "#PWD", $PWD.Path
$ArgumentList = $ArgumentList -replace "#SetupDirectory", ([System.IO.Path]::GetDirectoryName($Installer))
try {
# Perform the application install
switch ($Install.PackageInformation.SetupType) {
"EXE" {
Write-LogFile -Message "Installer: $Installer"
Write-LogFile -Message "ArgumentList: $ArgumentList"
$params = @{
FilePath = $Installer
ArgumentList = $ArgumentList
NoNewWindow = $true
PassThru = $true
Wait = $true
Verbose = $Script:VerbosePref
}
if ($PSCmdlet.ShouldProcess($Installer, $ArgumentList)) {
$result = Start-Process @params
}
}
"MSI" {
Write-LogFile -Message "Installer: $Env:SystemRoot\System32\msiexec.exe"
Write-LogFile -Message "ArgumentList: $ArgumentList"
$params = @{
FilePath = "$Env:SystemRoot\System32\msiexec.exe"
ArgumentList = $ArgumentList
NoNewWindow = $true
PassThru = $true
Wait = $true
Verbose = $Script:VerbosePref
}
if ($PSCmdlet.ShouldProcess("$Env:SystemRoot\System32\msiexec.exe", $ArgumentList)) {
$result = Start-Process @params
}
}
default {
Write-LogFile -Message "$($Install.PackageInformation.SetupType) not found in the supported setup types - EXE, MSI." -LogLevel 3
throw "$($Install.PackageInformation.SetupType) not found in the supported setup types - EXE, MSI."
}
}
# If wait specified, wait the specified seconds
if ($Install.InstallTasks.Wait -gt 0) { Start-Sleep -Seconds $Install.InstallTasks.Wait }
# Stop processes after installing the application
if ($Install.PostInstall.StopPath.Count -gt 0) { Stop-PathProcess -Path $Install.PostInstall.StopPath }
# Perform post install actions
if ($Install.PostInstall.Remove.Count -gt 0) { Remove-Path -Path $Install.PostInstall.Remove }
if ($Install.PostInstall.CopyFile.Count -gt 0) { Copy-File -File $Install.PostInstall.CopyFile }
# Execute run tasks
if ($Install.PostInstall.Run.Count -gt 0) {
foreach ($Task in $Install.PostInstall.Run) { Invoke-Expression -Command $Task }
}
}
catch {
Write-LogFile -Message $_.Exception.Message -LogLevel 3
throw $_
}
finally {
Write-LogFile -Message "Install.ps1 complete. Exit Code: $($result.ExitCode)"
exit $result.ExitCode
}
}
#endregion