WindowsInstaller.psm1

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
Set-StrictMode -Version Latest

function Get-MsiexecInstallString
{
    [OutputType([string])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$InstallerFilePath,
    
        [Parameter()]
        [AllowNull()]
        [string]$MstFilePath,
    
        [Parameter()]
        [AllowNull()]
        [string]$MspFilePath,
    
        [Parameter()]
        [AllowNull()]
        [string]$ExtraSwitches,
    
        [Parameter()]
        [AllowNull()]
        [string]$LogFilePath
    )
    begin {
        $ErrorActionPreference = 'Stop'
    }
    process {
        try
        {
            ## We're creating common msiexec switches here. /i specifies I want to run an install, /qn
            ## says I want that install to be quiet (no prompts) and n means no UI so no progress bars
            $InstallArgs = @()
            $InstallArgs += "/i `"$InstallerFilePath`" /qn"
            if ($MstFilePath)
            {
                $InstallArgs += "TRANSFORMS=`"$MstFilePath`""
            }
            if ($MspFilePath)
            {
                $InstallArgs += "PATCH=`"$MspFilePath`""
            }
            if ($ExtraSwitches)
            {
                $InstallArgs += $ExtraSwitches
            }
            
            ## Once we've added all of the custom syntax elements we'll then add a few more default
            ## switches. REBOOT=ReallySuppress prevents the computer from rebooting if it exists with an
            ## exit code of 3010, ALLUSERS=1 means that we'd like to make this software for all users
            ## on the machine and /Lvx* is the most verbose way to specify a log file path and to log as
            ## much information as possible.
            if (-not $PSBoundParameters.ContainsKey('LogFilePath'))
            {
                $LogFilePath = "$(Get-SystemTempFolderPath)\$($InstallerFilePath | Split-Path -Leaf).log"
            }
            $InstallArgs += "REBOOT=ReallySuppress ALLUSERS=1 /Lvx* `"$LogFilePath`""
            $InstallArgs = $InstallArgs -join ' '
            $InstallArgs
        }
        catch
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}

function Uninstall-ViaMsizap
{
    <#
    .SYNOPSIS
        This function runs the MSIzap utility to forcefully remove and cleanup MSI-installed software
    .DESCRIPTION
        This function runs msizap to remove software.
    .EXAMPLE
        Uninstall-ViaMsizap -MsizapFilePath C:\msizap.exe -Guid {XXXX-XXX-XXX}
        This example would attempt to remove the software registered with the GUID {XXXX-XXX-XXX}.
    .PARAMETER MsizapFilePath
        The file path where the msizap utility exists. This can be a local or UNC path.
    .PARAMETER Guid
        The GUID of the registered software you'd like removed
    .PARAMETER Params
        Non-default params you'd like passed to msizap. By default, "TWG!" is used to remove in all user
        profiles. This typically doesn't need to be changed.
    .PARAMETER LogFilePath
        The file path to where msizap will generate output
    #>

    [OutputType()]
    [CmdletBinding()]
    param (
        [ValidatePattern('\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b')]
        [Parameter(Mandatory = $true)]
        [string]$Guid,
        
        [string]$Params = 'TWG!',
        
        [ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
        [string]$MsizapFilePath = "C:\MyDeployment\msizap.exe",
        
        [Parameter()]
        [string]$LogFilePath = "$(Get-SystemTempFolderPath)\msizap.log"
    )
    process
    {
        try
        {
            Write-Log -Message "-Starting the process `"$MsiZapFilePath $Params $Guid`"..."
            $NewProcess = Start-Process $MsiZapFilePath -ArgumentList "$Params $Guid" -Wait -NoNewWindow -PassThru -RedirectStandardOutput $LogFilePath
            Wait-MyProcess -ProcessId $NewProcess.Id    
        }
        catch
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}

function Uninstall-WindowsInstallerPackage
{
    <#
    .SYNOPSIS
        This function runs an uninstall for a Windows Installer package
    .PARAMETER Name
        The software title of the Windows installer package you'd like to uninstall. Use either the Name
        param or the Guid param to find the Windows installer package.
    .PARAMETER MsiExecSwitches
        Specify a string of switches you'd like msiexec.exe to run when it attempts to uninstall the software. By default,
        it already uses "/x GUID /qn". You can specify any additional parameters here.
    .PARAMETER Guid
        The GUID of the Windows Installer package
    #>

    [OutputType()]
    [CmdletBinding(DefaultParameterSetName = 'Guid')]
    param (
        [Parameter(ParameterSetName = 'Name')]
        [string]$Name,
        
        [Parameter(ParameterSetName = 'Guid')]
        [ValidatePattern('\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b')]
        [string]$Guid,
        
        [string]$MsiExecSwitches
    )
    process
    {
        try
        {
            $Params = @{ }
            if ($Name)
            {
                Write-Log -Message "Attempting to uninstall Windows Installer using name '$Name'..."
                $params.Name = $Name
            }
            elseif ($Guid)
            {
                Write-Log -Message "Attempting to uninstall Windows Installer using GUID '$Guid'..."
                $params.Guid = $Guid
            }
            if ($PSBoundParameters.ContainsKey('MsiExecSwitches'))
            {
                $params.MsiExecSwitches = $MsiExecSwitches
            }
            
            if (Uninstall-WindowsInstallerPackageWithMsiexec @params)
            {
                Write-Log -Message 'Successfull uninstall.'
            }
            else
            {
                throw "Failed to uninstall."
            }
            
        }
        catch
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}

function Uninstall-WindowsInstallerPackageWithMsiexec
{
    <#
    .SYNOPSIS
        This function runs an uninstall for a Windows Installer package using msiexec.exe /x
    .PARAMETER Name
        The software title of the Windows installer package you'd like to uninstall. Use either the Name
        param or the Guid param to find the Windows installer package.
    .PARAMETER Guid
        The GUID of the Windows Installer package
    .PARAMETER MsiExecSwitches
        Specify a string of switches you'd like msiexec.exe to run when it attempts to uninstall the software. By default,
        it already uses "/x GUID /qn". You can specify any additional parameters here.
    #>

    [OutputType()]
    [CmdletBinding(DefaultParameterSetName = 'Guid')]
    param (
        [Parameter(ParameterSetName = 'Name')]
        [string]$Name,
        
        [Parameter(ParameterSetName = 'Guid')]
        [ValidatePattern('\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b')]
        [string]$Guid,
        
        [string]$MsiExecSwitches
    )
    process
    {
        try {
            if ($Name)
            {
                Write-Log -Message "Attempting to uninstall Windows Installer with msiexec.exe using name '$Name'..."
                $Params = @{ 'Name' = $Name }
                $software = Get-InstalledSoftware @Params
                if (-not $software)
                {
                    throw 'Name specified for uninstall but could not find GUID to remove'
                }
                else
                {
                    ## Sometimes multiple instances are returned. 1 having no GUID and 1 having a GUID.
                    ## Cisco AnyConnect is an example where if the one with the GUID is removed both are removed.
                    $Guid = $software | Where-Object { $_.GUID }
                    if (-not $Guid)
                    {
                        throw 'Required GUID could not be found for software'
                    }
                    else
                    {
                        $Guid = $Guid.GUID
                        Write-Log -Message "Using GUID [$Guid] for the uninstall"
                    }
                }
            }
            
            $switches = @("/x `"$Guid`"")
            if ($PSBoundParameters.ContainsKey('MsiExecSwitches'))
            {
                $switches += $MsiExecSwitches
            }
            $switches += @('REBOOT=ReallySuppress', '/qn')
            $switchString = $switches -join ' '
            
            Write-Log -Message "Initiating msiexec.exe with arguments [$($switchString)]"
            $Process = Start-Process 'msiexec.exe' -ArgumentList $switchString -PassThru -Wait -NoNewWindow
            Wait-WindowsInstaller
            Test-Process $Process
            if (-not (Test-InstalledSoftware -Guid $Guid))
            {
                Write-Log -Message 'Successfully uninstalled MSI package with msiexec.exe'
            }
            else
            {
                throw 'Failed to uninstall MSI package with msiexec.exe'
            }
        }
        catch 
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
        
    }
}

function Uninstall-WindowsInstallerPackageWithMsiModule
{
    <#
    .SYNOPSIS
        This function runs an uninstall for a Windows Installer package using the Windows Installer Powershell module
        https://psmsi.codeplex.com
    .PARAMETER Name
        The software title of the Windows installer package you'd like to uninstall. Use either the Name
        param or the Guid param to find the Windows installer package.
    .PARAMETER Guid
        The GUID of the Windows Installer package
    #>

    [OutputType()]
    [CmdletBinding(DefaultParameterSetName = 'Guid')]
    param (
        [Parameter(ParameterSetName = 'Name')]
        [string]$Name,
        
        [Parameter(ParameterSetName = 'Guid')]
        [ValidatePattern('\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b')]
        [string]$Guid
    )
    process
    {
        try
        {    
            if (-not (Get-Module -ListAvailable -Name 'MSI'))
            {
                throw 'Required MSI module is not available'
            }
            
            if (((Get-OperatingSystem) -notmatch 'XP') -and ((Get-OperatingSystem) -notmatch 'Server'))
            {
                $UninstallParams = @{
                    'Log' = $script:LogFilePath
                    'Chain' = $true
                    'Force' = $true
                    'ErrorAction' = 'SilentlyContinue'
                    'Properties' = 'REBOOT=ReallySuppress'
                }
                
                if ($Name)
                {
                    $MsiProductParams = @{ 'Name' = $Name }
                }
                elseif ($Guid)
                {
                    $MsiProductParams = @{ 'ProductCode' = $Guid }
                }
                
                Get-MSIProductInfo @MsiProductParams | Uninstall-MsiProduct @UninstallParams
                if (-not (Test-InstalledSoftware @MsiProductParams))
                {
                    Write-Log -Message "Successfully uninstalled MSI package '$Name' with MSI module"
                }
                else
                {
                    throw "Failed to uninstall MSI package '$Name' with MSI module"
                }
            }
            
        }
        catch
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}

function Wait-WindowsInstaller
{
    <#
    .SYNOPSIS
        This function should be called immediately after the Uninstall-WindowsInstallerPackage function. This is a specific
        process waiting function especially for msiexec.exe. It was built because the Wait-MyProcess function will sometimes
        not work with msiexec installs/uninstalls. This is because msiexec.exe creates a process tree which does not necessarily
        mean child processes. Using this function will ensure your script always wait for the msiexec.exe process you
        kicked off to complete before continuing.
    #>

    [OutputType()]
    [CmdletBinding()]
    param ()
    process
    {
        try
        {
            
            Write-Log -Message 'Looking for any msiexec.exe processes...'
            $MsiexecProcesses = Get-WmiObject -Class Win32_Process -Filter "Name = 'msiexec.exe'" | Where-Object { $_.CommandLine -ne 'C:\Windows\system32\msiexec.exe /V' }
            if ($MsiExecProcesses)
            {
                Write-Log -Message "Found '$($MsiexecProcesses.Count)' Windows installer processes. Waiting..."
                ## Wait for each msiexec.exe process to finish before proceeding
                foreach ($Process in $MsiexecProcesses)
                {
                    Wait-MyProcess -ProcessId $Process.ProcessId
                }
                ## When all msiexec.exe processes finish, recursively call this function again to ensure no
                ## other installs have begun.
                Wait-WindowsInstaller
            }
            else
            {
                Write-Log -Message 'No Windows installer processes found'
            }
        }
        catch
        {
            Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3'
            $PSCmdlet.ThrowTerminatingError($_)
        }
    }
}