-
Notifications
You must be signed in to change notification settings - Fork 38
/
Install.ps1
1896 lines (1766 loc) · 96.7 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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Helper script for installing/uninstalling Microsoft Defender for Downlevel Servers.
.DESCRIPTION
On install scenario:
It first removes MMA workspace when RemoveMMA guid is provided.
Next uninstalls SCEP if present and OS version is Server2012R2
Next installs two hotfixes required by the MSI (if they are not installed)
Next installs the Microsoft Defender for Downlevel Servers MSI (i.e. md4ws.msi)
Finally, it runs the onboarding script, if provided using the parameter OnboardingScript.
Please use the script for Group Policy as it is non-interactive; the local onboarding script will fail.
On uninstall scenario:
It will run the offboarding script, if provided.
Uninstalls the MSI unless IsTamperProtected is on.
Removes Defender Powershell module, if loaded inside current Powershell session.
.INPUTS
md4ws.msi
.OUTPUTS
none
.EXAMPLE
.\Install.ps1
.EXAMPLE
.\Install.ps1 -UI -NoMSILog -NoEtl
.EXAMPLE
.\Install.ps1 -Uninstall
.EXAMPLE
.\Install.ps1 -Uninstall -NoEtl
#>
param(
[Parameter(ParameterSetName = 'install')]
## MMA Workspace Id to be removed
[guid] $RemoveMMA,
[Parameter(ParameterSetName = 'install')]
## Path to onboarding script (required by WD-ATP)
[string] $OnboardingScript,
[Parameter(ParameterSetName = 'install')]
## Installs devmode msi instead of the realeased one
[switch] $DevMode,
[Parameter(ParameterSetName = 'uninstall', Mandatory)]
## Uninstalls Microsoft Defender for Downlevel Servers. Offboarding has to be run manually prior to uninstall.
[switch] $Uninstall,
[Parameter(ParameterSetName = 'uninstall')]
[Parameter(ParameterSetName = 'install')]
## Offboarding script to run prior to uninstalling/reinstalling MSI
[string] $OffboardingScript,
[Parameter(ParameterSetName = 'install')]
[Parameter(ParameterSetName = 'uninstall')]
## Enables UI in MSI
[switch] $UI,
[Parameter(ParameterSetName = 'install')]
## Put WinDefend in passive mode.
[switch] $Passive,
[Parameter(ParameterSetName = 'install')]
[Parameter(ParameterSetName = 'uninstall')]
## Disable MSI Logging
[switch] $NoMSILog,
[Parameter(ParameterSetName = 'install')]
## Used to pass extra arguments to Invoke-WebRequest calls used by this script (like WebSession, Proxy, ProxyCredential)
[hashtable] $ExtraWebRequestOptions = @{},
[Parameter(ParameterSetName = 'install')]
[Parameter(ParameterSetName = 'uninstall')]
## Disable ETL logging
[switch] $NoEtl)
function Get-CommandLine {
<#
.synopsis
Returns the equivalent command line used to invoke a script
.DESCRIPTION
Returns the equivalent command line used to invoke a script
.EXAMPLE
Get-CommandLine $PSCmdLet.MyInvocation
#>
[CmdletBinding()]
[OutputType([string])]
## Usually $PSCmdLet.MyInvocation.
param([Parameter(ValueFromPipeline = $true, Position = 0)] [System.Management.Automation.InvocationInfo] $info)
process {
function EscapeString {
param([string] $s)
if ($null -ne $s -and ' ' -in $s -and $s[0] -ne '"') {
"`"{0}'" -f $s
}
else {
$s
}
}
[string] $commandLine = ''
if ($null -ne $info) {
$commandLine = EscapeString $info.MyCommand.Name
foreach ($boundparam in $info.BoundParameters.GetEnumerator()) {
$val = ''
foreach ($k in ($boundparam.Value)) {
$val += if ($val.Length) { ',' } else { ':' }
$val += if ($k -is [switch]) {
if ($k.ToBool()) { '$true' } else { '$false' }
}
else {
EscapeString $k
}
}
$commandLine += " -{0}{1}" -f $boundparam.Key, $val
}
foreach ($k in $info.UnboundArguments.GetEnumerator()) {
$commandLine += " {0}" -f (EscapeString $k)
}
}
return $commandLine
}
}
function Set-RegistryKey {
[CmdletBinding()]
param([Parameter(Mandatory)][string] $LiteralPath,
[Parameter(Mandatory)][string] $Name,
[Parameter(Mandatory)][object] $Value)
function Set-ContainerPath {
[CmdletBinding()]
param([Parameter(Mandatory)][string] $LiteralPath)
if (!(Test-Path -LiteralPath:$LiteralPath -PathType:Container)) {
$parent = Split-Path -Path:$LiteralPath -Parent
Set-ContainerPath -LiteralPath:$parent
$leaf = Split-Path -Path:$LiteralPath -Leaf
$null = New-Item -Path:$parent -Name:$leaf -ItemType:Directory
}
}
Set-ContainerPath -LiteralPath:$LiteralPath
Set-ItemProperty -LiteralPath:$LiteralPath -Name:$Name -Value:$Value
Trace-Message "$LiteralPath[$Name]=$Value" -SkipFrames:3
}
function Remove-RegistryKey {
[CmdletBinding()]
param (
[Parameter(Mandatory)][string] $LiteralPath
)
if (Test-Path -LiteralPath:$LiteralPath) {
Remove-Item -LiteralPath:$LiteralPath -Recurse -Force -ErrorAction SilentlyContinue -ErrorVariable err
if ($err.count -gt 0){
Trace-Message "Remove-Item $LiteralPath message: $err" -SkipFrames:3
} else {
Trace-Message "Removed registry key: $LiteralPath" -SkipFrames:3
}
}
}
[System.IO.StreamWriter] $Script:InstallLog = $null
Set-Variable -Name:'InstallPS1HKLM' -Value:'HKLM:\SOFTWARE\Microsoft\Microsoft Defender for Endpoint Install' -Option:Constant -Scope:Script
function Get-TraceMessage {
[OutputType([string])]
param(
[Parameter(Mandatory, Position = 0)] [string] $Message,
[Parameter(Position = 1)][uint16] $SkipFrames = 2,
[datetime] $Date = (Get-Date))
function Get-Time {
param([datetime] $Date = (Get-Date))
return $Date.ToString('yy/MM/ddTHH:mm:ss.fff')
}
[System.Management.Automation.CallStackFrame[]] $stackFrames = Get-PSCallStack
for ($k = $SkipFrames; $k -lt $stackFrames.Count; $k++) {
$currentPS = $stackFrames[$k]
if ($null -ne $currentPS.ScriptName -or $currentPS.FunctionName -eq "<ScriptBlock>") {
[int] $lineNumber = $currentPS.ScriptLineNumber
if ($null -ne $currentPS.ScriptName) {
$scriptFullName = $currentPS.ScriptName
}
else {
if ($null -eq (Get-Variable VMPosition -ErrorAction:Ignore)) {
$scriptFullName = '<interactive>'
}
else {
$lineNumber += $VMPosition.Line
$scriptFullName = $VMPosition.File
}
}
$scriptName = $scriptFullName.Substring(1 + $scriptFullName.LastIndexOf('\'))
return "[{0}:{1:00} {2} {3}:{4,-3}] {5}" -f $env:COMPUTERNAME, [System.Threading.Thread]::CurrentThread.ManagedThreadId, (Get-Time $date), $scriptName, $lineNumber, $message
}
}
throw "Cannot figure out the right caller for $SkipFrames, $stackFrames"
}
function Get-CurrentBootSession {
[CmdletBinding()]
[OutputType([string])]
param()
return (Get-CimInstance -ClassName:Win32_OperatingSystem).LastBootUpTime.ToString('yy/MM/ddTHH:mm:ss.fff')
}
function Exit-Install {
[CmdletBinding()]
param ([Parameter(Mandatory, Position = 0)] [string] $Message,
[Parameter(Mandatory)] [uint32] $ExitCode)
$fullMessage = Get-TraceMessage -Message:$Message
if ($Script:ERR_PENDING_REBOOT -eq $ExitCode) {
## Subsequent runs of this scripts will be able to detect if a reboot happend since it was requested
Set-RegistryKey -LiteralPath:$Script:InstallPS1HKLM -Name:'PendingReboot' -Value:$(Get-CurrentBootSession)
}
if ($null -ne $Script:InstallLog) {
$Script:InstallLog.WriteLine($fullMessage)
$exitMessage = Get-TraceMessage -Message ("Script will exit with code {0}(0x{0:x})" -f $ExitCode) -SkipFrames:1
$Script:InstallLog.WriteLine($exitMessage)
$Script:InstallLog.Close()
$Script:InstallLog = $null
}
Write-Error $fullMessage -ErrorAction:Continue
exit $ExitCode
}
function Trace-Message {
[CmdletBinding()]
param ([Parameter(Mandatory, Position = 0)] [string] $Message,
[Parameter(Position = 1)][uint16] $SkipFrames = 2,
[datetime] $Date = (Get-Date))
$fullMessage = Get-TraceMessage -Message:$Message -SkipFrames:$SkipFrames -Date:$Date
if ($null -ne $Script:InstallLog) {
$Script:InstallLog.WriteLine($fullMessage)
}
Write-Host $fullMessage
}
function Trace-Warning {
[CmdletBinding()]
param ([Parameter(Mandatory)] [string] $Message)
$fullMessage = Get-TraceMessage "WARNING: $message"
## not using Write-Warning is intentional.
if ($null -ne $Script:InstallLog) {
$Script:InstallLog.WriteLine($fullMessage)
}
Write-Host $fullMessage
}
function Use-Object {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[AllowEmptyString()] [AllowEmptyCollection()] [AllowNull()]
[Object]$InputObject,
[Parameter(Mandatory = $true)]
[scriptblock] $ScriptBlock,
[Object[]]$ArgumentList
)
try {
& $ScriptBlock @ArgumentList
}
catch {
throw
}
finally {
if ($null -ne $InputObject -and $InputObject -is [System.IDisposable]) {
$InputObject.Dispose()
}
}
}
function New-TempFile {
#New-TemporaryFile is not available on PowerShell 4.0.
[CmdletBinding()]
[OutputType('System.IO.FileInfo')]
param()
$path = [System.Io.Path]::GetTempPath() + [guid]::NewGuid().Guid + '.tmp'
return New-Object -TypeName 'System.IO.FileInfo' -ArgumentList:$path
}
function Get-Digest {
<#
.SYNOPSIS
Returns an unique digest dependent on $sa array
#>
param ([string[]] $sa)
$sb = New-Object -TypeName:'System.Collections.Generic.List[byte]'
$sha256 = [System.Security.Cryptography.SHA256]::Create()
foreach ($element in $sa) {
$null = $sb.AddRange($sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($element)))
}
$hash = $sha256.ComputeHash($sb.ToArray())
$sha256.Dispose()
$rez = New-Object -TypeName:'System.Text.StringBuilder'
foreach ($hb in $hash) {
$null = $rez.Append($hb.ToString('X2'))
}
return $rez.ToString()
}
function Get-ScriptVersion {
[CmdLetBinding()]
param([string] $LiteralPath)
## DO NOT EDIT THIS BLOCK - BEGIN
$version = @{
Major = '1'
Minor = '20231204'
Patch = '0'
Metadata = 'E8E12DEA'
}
## DO NOT EDIT THIS BLOCK - END
[bool] $seen = $false
$scriptLines = @(Get-Content -Path:$LiteralPath | ForEach-Object {
$line = $_
if (-not $seen) {
$seen = $line -ieq "#Copyright (C) Microsoft Corporation. All rights reserved."
if ($line -match "^\s*Metadata\s*=\s*'([0-9A-F]{8})'") {
# skip it
}
else {
$line
}
}
})
$digest = (Get-Digest -sa:$scriptLines).Substring(0, 8)
if ($digest -ne $version.Metadata) {
$version.Patch = '1'
}
return "$($version.Major).$($version.Minor).$($version.Patch)+$digest"
}
function Measure-Process {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateScript( { Test-Path -LiteralPath:$_ -PathType:Leaf })]
[string] $FilePath,
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]] $ArgumentList,
[switch] $PassThru,
[ValidateScript( { Test-Path -LiteralPath:$_ -PathType:Container })]
[string] $WorkingDirectory = (Get-Location).Path,
[uint16] $SkipFrames = 3)
Trace-Message "Running $FilePath $ArgumentList in $WorkingDirectory ..." -SkipFrames:$SkipFrames
$startParams = @{
FilePath = $FilePath
WorkingDirectory = $WorkingDirectory
Wait = $true
NoNewWindow = $true
PassThru = $true
RedirectStandardOutput = New-TempFile
RedirectStandardError = New-TempFile
}
if ($ArgumentList) {
$startParams.ArgumentList = $ArgumentList
}
$info = @{ ExitCode = 1 }
try {
Use-Object ($proc = Start-Process @startParams) {
param ($ArgumentList, $SkipFrames)
[TimeSpan] $runningTime = ($proc.ExitTime - $proc.StartTime).Ticks
$exitCode = $info.exitCode = $proc.ExitCode
$info.ExitTime = $proc.ExitTime
Get-Content -Path $startParams.RedirectStandardOutput | ForEach-Object {
Trace-Message "[StandardOutput]: $_" -Date:$info.ExitTime -SkipFrames:$(1 + $SkipFrames)
}
Get-Content -Path $startParams.RedirectStandardError | ForEach-Object {
Trace-Message "[StandardError]: $_" -Date:$info.ExitTime -SkipFrames:$(1 + $SkipFrames)
}
$commandLine = $(Split-Path -Path:$FilePath -Leaf)
if ($ArgumentList) {
$commandLine += " $ArgumentList"
}
$message = if (0 -eq $exitCode) {
"Command `"$commandLine`" run for $runningTime"
}
else {
"Command `"$commandLine`" failed with error $exitCode after $runningTime"
}
Trace-Message $message -SkipFrames:$SkipFrames
if (-not $PassThru -and 0 -ne $exitCode) {
exit $exitCode
}
} -ArgumentList:$ArgumentList, (2 + $SkipFrames)
}
catch {
throw
}
finally {
Remove-Item -LiteralPath:$startParams.RedirectStandardError.FullName -Force -ErrorAction:SilentlyContinue
Remove-Item -LiteralPath:$startParams.RedirectStandardOutput.FullName -Force -ErrorAction:SilentlyContinue
}
if ($PassThru) {
return $info.ExitCode
}
}
function Test-CurrentUserIsInRole {
[CmdLetBinding()]
param([string[]] $SIDArray)
foreach ($sidString in $SIDArray) {
$sid = New-Object System.Security.Principal.SecurityIdentifier($sidString)
$role = $sid.Translate([Security.Principal.NTAccount]).Value
if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole($role)) {
return $true
}
}
return $false
}
function Get-GuidHelper {
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory)] [string] $Name,
[Parameter(Mandatory)] [string] $Value,
[Parameter(Mandatory)] [string] $LiteralPath,
[Parameter(Mandatory)] [string] $Pattern
)
## guids are regenerated every time we change .wx{i,s} files
## @note: SilentlyContinue just in case $Path does not exist.
$result = @(Get-ChildItem -LiteralPath:$LiteralPath -ErrorAction:SilentlyContinue |
Where-Object { $_.GetValue($Name) -match $Value -and $_.PSChildName -match $Pattern } |
Select-Object -ExpandProperty:PSChildName)
if ($result.Count -eq 1) {
return $result[0]
}
return $null
}
function Get-UninstallGuid {
[CmdletBinding()]
param (
# Parameter help description
[Parameter(Mandatory)] [string] $DisplayName
)
$extraParams = @{
Name = 'DisplayName'
Value = $DisplayName
LiteralPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
Pattern = '^{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}}$'
}
return Get-GuidHelper @extraParams
}
function Get-CodeSQUID {
[CmdletBinding()]
param (
[string] $ProductName
)
if (-not (Get-PSDrive -Name:'HKCR' -ErrorAction:SilentlyContinue)) {
$null = New-PSDrive -Name:'HKCR' -PSProvider:Registry -Root:HKEY_CLASSES_ROOT -Scope:Script
Trace-Message "'HKCR' PSDrive created(script scoped)"
}
## msi!MsiGetProductInfoW
$extraParams = @{
Name = 'ProductName'
Value = $ProductName
LiteralPath = 'HKCR:\Installer\Products'
Pattern = '^[0-9a-f]{32}$'
}
return Get-GuidHelper @extraParams
}
function Test-IsAdministrator {
Test-CurrentUserIsInRole 'S-1-5-32-544'
}
function Get-FileVersion {
[OutputType([System.Version])]
[CmdletBinding()]
param([Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $File)
$versionInfo = [Diagnostics.FileVersionInfo]::GetVersionInfo($File)
New-Object System.Version $($versionInfo.FileMajorPart), $($versionInfo.FileMinorPart), $($versionInfo.FileBuildPart), $($versionInfo.FilePrivatePart)
}
function Get-OSVersion {
[OutputType([System.Version])]
[CmdletBinding()]
param ()
# [environment]::OSVersion.Version on PowerShell ISE has issues on 2012R2 (see https://devblogs.microsoft.com/scripting/use-powershell-to-find-operating-system-version/)
# Get-CIMInstance provides a string where we don't get the revision.
return Get-FileVersion -File:"$env:SystemRoot\system32\ntoskrnl.exe"
}
function Invoke-Member {
[CmdletBinding()]
param ( [Object] $ComObject,
[Parameter(Mandatory)] [string] $Method,
[System.Object[]] $ArgumentList)
if ($ComObject) {
return $ComObject.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod, $null, $ComObject, $ArgumentList)
}
}
function Invoke-GetProperty {
[CmdletBinding()]
param ( [Object] $ComObject,
[Parameter(Mandatory)] [string] $Property,
[Parameter(Mandatory)] [int] $Colummn)
if ($ComObject) {
return $ComObject.GetType().InvokeMember($Property, [System.Reflection.BindingFlags]::GetProperty, $null, $ComObject, $Colummn)
}
}
function ReleaseComObject {
[CmdletBinding()]
param ([Object] $ComObject)
if ($ComObject) {
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($ComObject)
}
}
function Get-MsiFilesInfo {
[CmdletBinding()]
param ([Parameter(Mandatory)] [string] $MsiPath)
function Get-MsiFileTableHelper {
param ([Parameter(Mandatory)] [Object] $Database)
try {
## @see https://docs.microsoft.com/en-us/windows/win32/msi/file-table
$view = Invoke-Member $Database 'OpenView' ("SELECT * FROM File")
Invoke-Member $view 'Execute'
$rez = @{}
while ($null -ne ($record = Invoke-Member $view 'Fetch')) {
$file = Invoke-GetProperty $record 'StringData' 1
$FileName = Invoke-GetProperty $record 'StringData' 3
$versionString = $(Invoke-GetProperty $record 'StringData' 5)
$version = if ($versionString) {
[version]$versionString
}
else {
$null
}
$rez.$file = [ordered] @{
Component = Invoke-GetProperty $record 'StringData' 2
FileName = $FileName
FileSize = [convert]::ToInt64($(Invoke-GetProperty $record 'StringData' 4))
Version = $version
Language = Invoke-GetProperty $record 'StringData' 6
Attributes = [convert]::ToInt16($(Invoke-GetProperty $record 'StringData' 7))
Sequence = [convert]::ToInt16($(Invoke-GetProperty $record 'StringData' 8))
}
ReleaseComObject $record
}
return $rez
}
catch {
throw
}
finally {
Invoke-Member $view 'Close'
ReleaseComObject $view
}
}
try {
$installer = New-Object -ComObject:WindowsInstaller.Installer
## @see https://docs.microsoft.com/en-us/windows/win32/msi/database-object
$database = Invoke-Member $installer 'OpenDatabase' ($MsiPath, 0)
return Get-MsiFileTableHelper -Database:$database
}
catch {
throw
}
finally {
ReleaseComObject $database
ReleaseComObject $installer
}
}
function Test-ExternalScripts {
[CmdletBinding()]
param ()
if ($OnboardingScript.Length) {
if (-not (Test-Path -LiteralPath:$OnboardingScript -PathType:Leaf)) {
Exit-Install -Message:"$OnboardingScript does not exist" -ExitCode:$ERR_ONBOARDING_NOT_FOUND
}
## validate it is an "onboarding" script.
$on = Get-Content -LiteralPath:$OnboardingScript | Where-Object {
$_ -match 'add\s+"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Advanced Threat Protection"\s+\/v\s+OnboardingInfo'
}
if ($on.Length -eq 0) {
Exit-Install -Message:"Not an onboarding script: $OnboardingScript" -ExitCode:$ERR_INVALID_PARAMETER
}
if (-not (Test-IsAdministrator)) {
Exit-Install -Message:'Onboarding scripts need to be invoked from an elevated process' -ExitCode:$ERR_INSUFFICIENT_PRIVILEGES
}
$pause = Get-Content -LiteralPath:$OnboardingScript | Where-Object { $_ -imatch '^pause$' }
if ($pause.Length -ne 0) {
## Please read: https://github.com/microsoft/mdefordownlevelserver#project
Exit-Install -Message:"Please use the onboarding script for Group Policy as it is non-interactive, $OnboardingScript might wait for user input" -ExitCode:$ERR_INVALID_SCRIPT_TYPE
}
}
if ($OffboardingScript.Length) {
if (-not (Test-Path -LiteralPath:$OffboardingScript -PathType:Leaf)) {
Exit-Install -Message:"$OffboardingScript does not exist" -ExitCode:$ERR_OFFBOARDING_NOT_FOUND
}
$off = Get-Content -LiteralPath:$OffboardingScript | Where-Object {
$_ -match 'add\s+"HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Advanced Threat Protection"\s+\/v\s+696C1FA1-4030-4FA4-8713-FAF9B2EA7C0A'
}
if ($off.Length -eq 0) {
Exit-Install -Message:"Not an offboarding script: $OffboardingScript" -ExitCode:$ERR_INVALID_PARAMETER
}
if (-not (Test-IsAdministrator)) {
Exit-Install -Message:'Offboarding scripts need to be invoked from an elevated process' -ExitCode:$ERR_INSUFFICIENT_PRIVILEGES
}
$pause = Get-Content -LiteralPath:$OffboardingScript | Where-Object { $_ -imatch '^pause$' }
if ($pause.Length -ne 0) {
## Please read: https://github.com/microsoft/mdefordownlevelserver#project
Exit-Install -Message:"Please use the offboarding script for Group Policy as it is non-interactive, $OffboardingScript might wait for user input" -ExitCode:$ERR_INVALID_SCRIPT_TYPE
}
}
}
function Get-RegistryKey {
[CmdLetBinding()]
param([Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $LiteralPath,
[Parameter(Mandatory)][ValidateNotNullOrEmpty()][string] $Name)
## @note: Get-ItemPropertyValue ... -ErrorAction:SilentlyContinue is complaining about errors.
$k = Get-ItemProperty -LiteralPath:$LiteralPath -Name:$Name -ErrorAction:SilentlyContinue
if ($k) {
return $k.$Name
}
return $null
}
function Invoke-MpCmdRun {
[CmdLetBinding()]
param(
[AllowEmptyString()] [AllowEmptyCollection()] [string[]] $ArgumentList,
[uint16] $SkipFrames = 4
)
$startParams = @{
FilePath = Join-Path -Path:$(Get-RegistryKey -LiteralPath:'HKLM:\SOFTWARE\Microsoft\Windows Defender' -Name:'InstallLocation') 'MpCmdRun.exe'
SkipFrames = $SkipFrames
}
if ($ArgumentList) {
$startParams.ArgumentList = $ArgumentList
}
Measure-Process @startParams
}
function Start-TraceSession {
[CmdLetBinding()]
param()
$guid = [guid]::NewGuid().Guid
$wdprov = Join-Path -Path:$env:TEMP "$guid.temp"
$tempFile = Join-Path -Path:$env:TEMP "$guid.etl"
$etlLog = "$PSScriptRoot\$logBase.etl"
$wppTracingLevel = 'WppTracingLevel'
$reportingPath = 'HKLM:\Software\Microsoft\Windows Defender\Reporting'
$etlParams = @{
ArgumentList = @($PSScriptRoot, $logBase, $wdprov, $tempFile, $etlLog, $wppTracingLevel, $reportingPath)
}
if (-not (Test-IsAdministrator)) {
# non-administrator should be able to install.
$etlParams.Credential = Get-Credential -UserName:Administrator -Message:"Administrator credential are required for starting an ETW session:"
$etlParams.ComputerName = 'localhost'
$etlParams.EnableNetworkAccess = $true
}
if (Test-Path -LiteralPath:$etlLog -PathType:leaf) {
if (Test-Path -LiteralPath:"$PSScriptRoot\$logBase.prev.etl") {
Remove-Item -LiteralPath:"$PSScriptRoot\$logBase.prev.etl" -ErrorAction:Stop
}
Rename-Item -LiteralPath:$etlLog -NewName:"$logBase.prev.etl" -ErrorAction:Stop
}
$scmWppTracingKey = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Tracing\SCM\Regular'
$scmWppTracingValue = 'TracingDisabled'
$scmTracingDisabled = Get-RegistryKey -LiteralPath:$scmWppTracingKey -Name:$scmWppTracingValue
if (1 -eq $scmTracingDisabled) {
## certain SCM issues could be investigated only if ebcca1c2-ab46-4a1d-8c2a-906c2ff25f39 is enabled.
## Unfortunatelly SCM does not register ebcca1c2-ab46-4a1d-8c2a-906c2ff25f39 when HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Tracing\SCM\Regular[TracingDisabled] is (DWORD)1,
## therefore it cannot be enabled / disabled without a restart.
Trace-Warning "Service Control Manager tracing is disabled (see $scmWppTracingKey[$scmWppTracingValue])"
}
Invoke-Command @etlparams -ScriptBlock: {
param($ScriptRoot, $logBase, $wdprov, $tempFile, $etlLog, $wppTracingLevel, $reportingPath);
## enable providers
$providers = @(
@{Guid = 'ebcca1c2-ab46-4a1d-8c2a-906c2ff25f39'; Flags = 0x0FFFFFFF; Level = 0xff; Name = "SCM" },
@{Guid = 'B0CA1D82-539D-4FB0-944B-1620C6E86231'; Flags = 0xffffffff; Level = 0xff; Name = 'EventLog' },
@{Guid = 'A676B545-4CFB-4306-A067-502D9A0F2220'; Flags = 0xfffff; Level = 0x5; Name = 'setup' },
@{Guid = '81abafee-28b9-4df5-bb2d-5b0be87829f5'; Flags = 0xff; Level = 0x1f; Name = 'mpwixca' },
@{Guid = '68edb168-7705-494b-a746-9297abdc91d3'; Flags = 0xff; Level = 0x1f; Name = 'mpsigstub' },
@{Guid = '2a94554c-2fbe-46d0-9fa6-60562281b0cb'; Flags = 0xff; Level = 0x1f; Name = 'msmpeng' },
@{Guid = 'db30e9dc-354d-48b5-9dc0-aeaebc5c6b54'; Flags = 0xff; Level = 0x1f; Name = 'mpclient' },
@{Guid = 'ac45fef1-612b-4066-85a7-dd0a5e8a7f30'; Flags = 0xff; Level = 0x1f; Name = 'mpsvc' },
@{Guid = '5638cd78-bc82-608a-5b69-c9c7999b411c'; Flags = 0xff; Level = 0x1f; Name = 'mpengine' },
@{Guid = '449df70e-dba7-42c8-ba01-4d0911a4aecb'; Flags = 0xff; Level = 0x1f; Name = 'mpfilter' },
@{Guid = 'A90E9218-1F47-49F5-AB71-9C6258BD7ECE'; Flags = 0xff; Level = 0x1f; Name = 'mpcmdrun' },
@{Guid = '0c62e881-558c-44e7-be07-56b991b9401a'; Flags = 0xff; Level = 0x1f; Name = 'mprtp' },
@{Guid = 'b702d31c-f586-4fc0-bcf5-f929745199a4'; Flags = 0xff; Level = 0x1f; Name = 'nriservice' },
@{Guid = '4bc60e5e-1e5a-4ec8-b0a3-a9efc31c6667'; Flags = 0xff; Level = 0x1f; Name = 'nridriver' },
@{Guid = 'FFBD47B1-B3A9-4E6E-9A44-64864363DB83'; Flags = 0xff; Level = 0x1f; Name = 'mpdlpcmd' },
@{Guid = '942bda7f-e07d-5a00-96d3-92f5bcb7f377'; Flags = 0xff; Level = 0x1f; Name = 'mpextms' },
@{Guid = 'bc4992b8-a44c-4f70-834b-9d45df9b1824'; Flags = 0xff; Level = 0x1f; Name = 'WdDevFlt' }
)
Set-Content -LiteralPath:$wdprov -Value:"# {PROVIDER_GUID}<space>FLAGS<space>LEVEL" -Encoding:ascii
$providers | ForEach-Object {
# Any line that starts with '#','*',';' is commented out
# '-' in front of a provider disables it.
# {PROVIDER_GUID}<space>FLAGS<space>LEVEL
Add-Content -LiteralPath:$wdprov -Value:("{{{0}}} {1} {2}" -f $_.Guid, $_.Flags, $_.Level) -Encoding:ascii
}
try {
$jobParams = @{
Name = "Setting up $wppTracingLevel"
ScriptBlock = {
param([string] $reportingPath, [string] $wppTracingLevel)
function Set-RegistryKey {
[CmdletBinding()]
param([Parameter(Mandatory)][string] $LiteralPath,
[Parameter(Mandatory)][string] $Name,
[Parameter(Mandatory)][object] $Value)
function Set-ContainerPath {
[CmdletBinding()]
param([Parameter(Mandatory)][string] $LiteralPath)
if (!(Test-Path -LiteralPath:$LiteralPath -PathType:Container)) {
$parent = Split-Path -Path:$LiteralPath -Parent
Set-ContainerPath -LiteralPath:$parent
$leaf = Split-Path -Path:$LiteralPath -Leaf
$null = New-Item -Path:$parent -Name:$leaf -ItemType:Directory
}
}
Set-ContainerPath -LiteralPath:$LiteralPath
Set-ItemProperty -LiteralPath:$LiteralPath -Name:$Name -Value:$Value
}
Set-RegistryKey -LiteralPath:$reportingPath -Name:$wppTracingLevel -Value:0 -ErrorAction:SilentlyContinue
}
ArgumentList = @($reportingPath, $wppTracingLevel)
ScheduledJobOption = New-ScheduledJobOption -RunElevated
}
try {
$scheduledJob = Register-ScheduledJob @jobParams -ErrorAction:Stop
$taskParams = @{
TaskName = $scheduledJob.Name
Action = New-ScheduledTaskAction -Execute $scheduledJob.PSExecutionPath -Argument:$scheduledJob.PSExecutionArgs
Principal = New-ScheduledTaskPrincipal -UserId:'NT AUTHORITY\SYSTEM' -LogonType:ServiceAccount -RunLevel:Highest
}
$scheduledTask = Register-ScheduledTask @taskParams -ErrorAction:Stop
Start-ScheduledTask -InputObject:$scheduledTask -ErrorAction:Stop -AsJob | Wait-Job | Remove-Job -Force -Confirm:$false
$SCHED_S_TASK_RUNNING = 0x41301
do {
Start-Sleep -Milliseconds:10
$LastTaskResult = (Get-ScheduledTaskInfo -InputObject:$scheduledTask).LastTaskResult
} while ($LastTaskResult -eq $SCHED_S_TASK_RUNNING)
}
catch {
Trace-Warning "Error: $_"
}
finally {
if ($scheduledJob) {
Unregister-ScheduledJob -InputObject $scheduledJob -Force
}
if ($scheduledTask) {
Unregister-ScheduledTask -InputObject $scheduledTask -Confirm:$false
}
}
$wpp = Get-RegistryKey -LiteralPath:$reportingPath -Name:$wppTracingLevel
if ($null -eq $wpp) {
Trace-Warning "$reportingPath[$wppTracingLevel] could not be created"
}
else {
Trace-Message "$reportingPath[$wppTracingLevel]=$wpp"
}
#Set-ItemProperty -LiteralPath:'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Tracing\SCM\Regular' -Name:'TracingDisabled' -Value:0
& logman.exe create trace -n $logBase -pf $wdprov -ets -o $tempFile *>$null
if (0 -eq $LASTEXITCODE) {
Trace-Message "Tracing session '$logBase' started."
}
else {
Trace-Warning "logman.exe create trace -n $logBase -pf $wdprov -ets -o $tempFile exited with exitcode $LASTEXITCODE"
}
}
catch {
throw
}
finally {
Remove-Item -LiteralPath:$wdprov -ErrorAction:Continue
}
}
return $etlParams
}
$currentDate = Get-Date
$Installps1LogName = "InstallPS1-$env:COMPUTERNAME.$($currentDate.ToString('yyMMddTHHmmssfffzzz').Replace(':', '')).log"
if (-not $NoMSILog.IsPresent -or -not $NoEtl.IsPresent) {
$InstallLogPath = Join-Path $PSScriptRoot -ChildPath:$Installps1LogName
try {
$Script:InstallLog = New-Object -TypeName:'System.IO.StreamWriter' -ArgumentList:@($InstallLogPath, $true)
Trace-Message "$($PSCmdLet.MyInvocation.MyCommand.Name) traces will be saved to $InstallLogPath"
}
catch {
Trace-Warning "Error: $_"
}
}
Trace-Message "Running command: $(Get-CommandLine $PSCmdLet.MyInvocation)"
@(
@{ Name = 'ERR_INTERNAL'; Value = 1 } ## Not used.
@{ Name = 'ERR_INSUFFICIENT_PRIVILEGES'; Value = 3 } ## Are you running as Administrator?
@{ Name = 'ERR_NO_INTERNET_CONNECTIVITY'; Value = 4 } ## Are you behind a proxy? Is network on?
@{ Name = 'ERR_CONFLICTING_APPS'; Value = 5 } ## Not used.
@{ Name = 'ERR_INVALID_PARAMETER'; Value = 6 } ## Are you providing the right parameters to this script? Did you missmatch **On**boardingScript with an **Off**boarding script or vice-versa?
@{ Name = 'ERR_UNSUPPORTED_DISTRO'; Value = 10 } ## Is this a server SKU? Is this '2012 R2' or '2016' Server?
@{ Name = 'ERR_UNSUPPORTED_VERSION'; Value = 11 } ## Uninstall using the regular Administator account (Using System was fixed in Feb 2023)
@{ Name = 'ERR_PENDING_REBOOT'; Value = 12 } ## A dependent component requested a reboot.
@{ Name = 'ERR_INSUFFICIENT_REQUIREMENTS'; Value = 13 } ## A requirement was not satisfied, cannot continue.
@{ Name = 'ERR_UNEXPECTED_STATE'; Value = 14 } ## Cannot handle the task in the current state of the product. Manual intervention is required.
@{ Name = 'ERR_CORRUPTED_FILE'; Value = 15 } ## All executable files (and this script) should be signed. Was one of the files (md4ws.msi) truncated?
@{ Name = 'ERR_MSI_NOT_FOUND'; Value = 16 } ## Is the MSI in the same directory like this file?
@{ Name = 'ERR_ALREADY_UNINSTALLED'; Value = 17 } ## Not used.
@{ Name = 'ERR_DIRECTORY_NOT_WRITABLE'; Value = 18 } ## Current directory should be writeable (to write the installation/uninstallation logs)
@{ Name = 'ERR_MDE_NOT_INSTALLED'; Value = 20 } ## Cannot uninstall something that is not installed.
@{ Name = 'ERR_INSTALLATION_FAILED'; Value = 21 } ## Not used.
@{ Name = 'ERR_UNINSTALLATION_FAILED'; Value = 22 } ## Not used.
@{ Name = 'ERR_FAILED_DEPENDENCY'; Value = 23 } ## Not used
@{ Name = 'ERR_ONBOARDING_NOT_FOUND'; Value = 30 } ## Check passed onboarding script path. Does it point to an existing file?
@{ Name = 'ERR_ONBOARDING_FAILED'; Value = 31 } ## Onboarding script failed.
@{ Name = 'ERR_OFFBOARDING_NOT_FOUND'; Value = 32 } ## Check passed offboarding script path. Does it point to an existing file?
@{ Name = 'ERR_OFFBOARDING_FAILED'; Value = 33 } ## Offboarding script failed.
@{ Name = 'ERR_NOT_ONBOARDED'; Value = 34 } ## Cannot offboard if not onboarded
@{ Name = 'ERR_NOT_OFFBOARDED'; Value = 35 } ## Cannot onboard if already onboarded.
@{ Name = 'ERR_MSI_USED_BY_OTHER_PROCESS'; Value = 36 } ## md4ws.msi is opened by a process (orca.exe?!), preventing a successful installation.
@{ Name = 'ERR_INVALID_SCRIPT_TYPE'; Value = 37 } ## Onboarding/Offboading scripts shouldn't require any user interaction.
@{ Name = 'ERR_TAMPER_PROTECTED'; Value = 38 } ## Uninstallation cannot continue, since the product is still tamper protected.
@{ Name = 'ERR_MDE_GROUP_POLICY_DISABLED'; Value = 39 } ## HKLM:\Software\Policies\Microsoft\Windows Defender[DisableAntiSpyware] is set to 1.
) | ForEach-Object {
Set-Variable -Name:$_.Name -Value:$_.Value -Option:Constant -Scope:Script
}
if (-not [System.Environment]::Is64BitOperatingSystem) {
Exit-Install "Only 64 bit OSes (Server 2012 R2 or Server 2016) are currently supported by this script" -ExitCode:$ERR_UNSUPPORTED_DISTRO
}
elseif (-not [System.Environment]::Is64BitProcess) {
Trace-Warning "Current process IS NOT 64bit. Did you start a 'Windows Powershell (x86)'?!"
$nativePowershell = "$env:SystemRoot\sysnative\windowspowershell\v1.0\powershell.exe"
if (-not (Test-Path -LiteralPath:$nativePowershell -PathType:Leaf)) {
Exit-Install "Cannot figure out 64 bit powershell location. Please run this script from a 64bit powershell." -ExitCode:$ERR_UNEXPECTED_STATE
}
[System.Collections.ArrayList] $argumentList = New-Object -TypeName:'System.Collections.ArrayList'
$argumentList.AddRange(@('-NoProfile', '-NonInteractive', '-File', $MyInvocation.MyCommand.Path))
if ($MyInvocation.BoundParameters.Count -gt 0) {
function Get-EscapeString {
param([string] $s)
if ($null -ne $s -and ' ' -in $s -and $s[0] -ne '"') {
"`"{0}'" -f $s
}
else {
$s
}
}
foreach ($boundparam in $MyInvocation.BoundParameters.GetEnumerator()) {
if ($boundparam.Value -is [switch]) {
if ($boundparam.Value.ToBool()) {
$null = $argumentList.Add($("-{0}" -f $boundparam.Key))
}
}
else {
$val = ''
foreach ($k in ($boundparam.Value)) {
$val += if ($val.Length) { ',' } else { ':' }
$val += Get-EscapeString $k
}
$null = $argumentList.Add($("-{0}{1}" -f $boundparam.Key, $val))
}
}
foreach ($k in $MyInvocation.UnboundArguments.GetEnumerator()) {
$null = $argumentList.Add($("{0}" -f (Get-EscapeString $k)))
}
}
$psArgumentList = $argumentList.ToArray()
Trace-Message "Running $nativePowershell $psArgumentList"
& $nativePowershell $psArgumentList
if (-not $?) {
Trace-Warning "$nativePowershell $psArgumentList exited with exitcode $LASTEXITCODE"
}
exit $LASTEXITCODE
}
Test-ExternalScripts
if ('Tls12' -notin [Net.ServicePointManager]::SecurityProtocol) {
## Server 2016/2012R2 might not have this one enabled and all Invoke-WebRequest might fail.
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Trace-Message "[Net.ServicePointManager]::SecurityProtocol updated to '$([Net.ServicePointManager]::SecurityProtocol)'"
}
if ($null -eq $ExtraWebRequestOptions) {
$ExtraWebRequestOptions = @{}
}
else {
## validate ExtraWebRequestOptions hash
[bool] $validExtraWebRequestOptions = $true
foreach ($useOption in 'Uri', 'OutFile', 'ErrorAction', 'UseBasicParsing') {
if ($ExtraWebRequestOptions.ContainsKey($useOption)) {
Trace-Warning "Please remove $useOption from ExtraWebRequestOption hash and try again."
$validExtraWebRequestOptions = $false
}
}
if (-not $validExtraWebRequestOptions) {
Exit-Install -Message:"Invalid parameter ExtraWebRequestOption (see the above warnings)" -ExitCode:$ERR_INVALID_PARAMETER
}
}
$osVersion = Get-OSVersion
## make sure we capture logs by default.
[bool] $etl = -not $NoEtl.IsPresent
[bool] $log = -not $NoMSILog.IsPresent
[string] $msi = if ($DevMode.IsPresent -or ((Test-Path -Path:"$PSScriptRoot\md4ws-devmode.msi") -and -not (Test-Path -Path:"$PSScriptRoot\md4ws.msi"))) {
## This is used internally (never released to the public) by product team to test private builds.
Join-Path -Path:$PSScriptRoot "md4ws-devmode.msi"
}
else {
Join-Path -Path:$PSScriptRoot "md4ws.msi"
}
$action = if ($Uninstall.IsPresent) { 'uninstall' } else { 'install' }
$logBase = "$action-$env:COMPUTERNAME"
if ($etl -or $log) {
## make sure $PSSCriptRoot is writable.
$tempFile = Join-Path -Path:$PSScriptRoot "$([guid]::NewGuid().Guid).tmp"
Set-Content -LiteralPath:$tempFile -Value:'' -ErrorAction:SilentlyContinue
if (-not (Test-Path -LiteralPath:$tempFile -PathType:Leaf)) {
Exit-Install "Cannot create $tempFile. Is $PSScriptRoot writable?" -ExitCode:$ERR_DIRECTORY_NOT_WRITABLE
}
else {
Remove-Item -LiteralPath:$tempFile -ErrorAction:SilentlyContinue
$tempFile = $null
}
}
$etlParams = @{}
try {
$tempMsiLog = Join-Path -Path:$env:TEMP "$([guid]::NewGuid().Guid).log"
[System.IO.FileStream] $msiStream = $null
if ($action -eq 'install') {
## $msi should be checked as early as possible, see ICM#413339981
if (-not (Test-Path -LiteralPath:$msi -PathType:leaf)) {
Exit-Install "$msi does not exist. Please download latest $(Split-Path -Path:$msi -Leaf) into $PSScriptRoot and try again." -ExitCode:$ERR_MSI_NOT_FOUND
}
else {
try {
$msiStream = [System.IO.File]::OpenRead($msi)
Trace-Message ("Handle {0} opened over {1}" -f $msiStream.SafeFileHandle.DangerousGetHandle(), $msi)
}
catch {
## Orca (https://docs.microsoft.com/en-us/windows/win32/msi/orca-exe) likes to keep a opened handle to $msi
## and if installation happens during this time Get-AuthenticodeSignature will get an 'Unknown' status.
## Same with msiexec.exe, so better check for this scenario here.
Exit-Install "Cannot open $msi for read: $_.Exception" -ExitCode:$ERR_MSI_USED_BY_OTHER_PROCESS
}
$status = (Get-AuthenticodeSignature -FilePath:$msi).Status
if ($status -ne 'Valid') {
Exit-Install "Unexpected authenticode signature status($status) for $msi" -ExitCode:$ERR_CORRUPTED_FILE
}
Trace-Message "$($(Get-FileHash -LiteralPath:$msi).Hash) $msi"
}
}
if ($null -ne $RemoveMMA) {
$mma = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg'
$workspaces = @($mma.GetCloudWorkspaces() | Select-Object -ExpandProperty:workspaceId)
if ($RemoveMMA -in $workspaces) {
Trace-Message "Removing cloud workspace $($RemoveMMA.Guid)..."
$mma.RemoveCloudWorkspace($RemoveMMA)
$workspaces = @($mma.GetCloudWorkspaces() | Select-Object -ExpandProperty:workspaceId)
if ($workspaces.Count -gt 0) {
$mma.ReloadConfiguration()
}
else {
Stop-Service HealthService