-
Notifications
You must be signed in to change notification settings - Fork 209
/
LabTech.psm1
3771 lines (3286 loc) · 173 KB
/
LabTech.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
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
This is a PowerShell Module for LabTech.
labtechconsulting.com
labtechsoftware.com
msdn.microsoft.com/powershell
.DESCRIPTION
This is a set of commandlets to interface with the LabTech Agent.
Tested Versions: v10.5-v12, v2019-v2024
.NOTES
Version: 1.9.2
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 1/23/2018
Purpose/Change: Updates to address 32-bit vs. 64-bit environments
Update Date: 2/1/2018
Purpose/Change: Updates for support of Proxy Settings. Enabled -WhatIf processing for many functions.
Update Date: 8/7/2018
Purpose/Change: Added support for TLS 1.2
Update Date: 8/28/2018
Purpose/Change: Added Update-LTService function
Update Date: 2/26/2019
Purpose/Change: Update to support 32-bit execution in 64-bit OS without SYSNATIVE redirection
Update Date: 9/9/2020
Purpose/Change: Update to support 64-bit OS without SYSNATIVE redirection (ARM64)
#>
If (-not ($PSVersionTable)) {Write-Warning 'PS1 Detected. PowerShell Version 2.0 or higher is required.';return}
ElseIf ($PSVersionTable.PSVersion.Major -lt 3 ) {Write-Verbose 'PS2 Detected. PowerShell Version 3.0 or higher may be required for full functionality.'}
#Module Version
$ModuleVersion = "1.9.2"
$ModuleGuid='f1f06c84-00c8-11ea-b6e8-000c29aaa7df'
If ($env:PROCESSOR_ARCHITEW6432 -match '64' -and [IntPtr]::Size -ne 8 -and $env:PROCESSOR_ARCHITEW6432 -ne 'ARM64') {
Write-Warning '32-bit PowerShell session detected on 64-bit OS. Attempting to launch 64-Bit session to process commands.'
$pshell="${env:windir}\SysNative\WindowsPowershell\v1.0\powershell.exe"
If (!(Test-Path -Path $pshell)) {
$pshell="${env:windir}\System32\WindowsPowershell\v1.0\powershell.exe"
If ($Null -eq ([System.Management.Automation.PSTypeName]'Kernel32.Wow64').Type -or $Null -eq [Kernel32.Wow64].GetMethod('Wow64DisableWow64FsRedirection')) {
Write-Debug 'Loading WOW64Redirection functions'
Add-Type -Name Wow64 -Namespace Kernel32 -Debug:$False -MemberDefinition @"
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool Wow64RevertWow64FsRedirection(ref IntPtr ptr);
"@
}
Write-Verbose 'System32 path is redirected. Disabling redirection.'
[ref]$ptr = New-Object System.IntPtr
$Result = [Kernel32.Wow64]::Wow64DisableWow64FsRedirection($ptr)
$FSRedirectionDisabled=$True
}#End If
If ($myInvocation.Line) {
&"$pshell" -NonInteractive -NoProfile $myInvocation.Line
} Elseif ($myInvocation.InvocationName) {
&"$pshell" -NonInteractive -NoProfile -File "$($myInvocation.InvocationName)" $args
} Else {
&"$pshell" -NonInteractive -NoProfile $myInvocation.MyCommand
}#End If
$ExitResult=$LASTEXITCODE
If ($Null -ne ([System.Management.Automation.PSTypeName]'Kernel32.Wow64').Type -and $Null -ne [Kernel32.Wow64].GetMethod('Wow64DisableWow64FsRedirection') -and $FSRedirectionDisabled -eq $True) {
[ref]$defaultptr = New-Object System.IntPtr
$Result = [Kernel32.Wow64]::Wow64RevertWow64FsRedirection($defaultptr)
Write-Verbose 'System32 path redirection has been re-enabled.'
}#End If
Write-Warning 'Exiting 64-bit session. Module will only remain loaded in native 64-bit PowerShell environment.'
Exit $ExitResult
}#End If
#Ignore SSL errors
If ($Null -eq ([System.Management.Automation.PSTypeName]'TrustAllCertsPolicy').Type) {
Add-Type -Debug:$False @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
}
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
#Enable TLS, TLS1.1, TLS1.2, TLS1.3 in this session if they are available
IF([Net.SecurityProtocolType]::Tls) {[Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls}
IF([Net.SecurityProtocolType]::Tls11) {[Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls11}
IF([Net.SecurityProtocolType]::Tls12) {[Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12}
IF([Net.SecurityProtocolType]::Tls13) {[Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls13}
#region [Functions]-------------------------------------------------------------
Function Get-LTServiceInfo{
<#
.SYNOPSIS
This function will pull all of the registry data into an object.
.NOTES
Version: 1.5
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 8/24/2017
Purpose/Change: Update to use Clear-Variable.
Update Date: 3/12/2018
Purpose/Change: Support for ShouldProcess to enable -Confirm and -WhatIf.
Update Date: 8/28/2018
Purpose/Change: Remove '~' from server addresses.
Update Date: 1/19/2019
Purpose/Change: Improved BasePath value assignment
.LINK
http://labtechconsulting.com
#>
[CmdletBinding(SupportsShouldProcess=$True, ConfirmImpact='Low')]
Param ()
Begin{
Write-Debug "Starting $($myInvocation.InvocationName) at line $(LINENUM)"
Clear-Variable key,BasePath,exclude,Servers -EA 0 -WhatIf:$False -Confirm:$False #Clearing Variables for use
$exclude = "PSParentPath","PSChildName","PSDrive","PSProvider","PSPath"
$key = $Null
}#End Begin
Process{
If ((Test-Path 'HKLM:\SOFTWARE\LabTech\Service') -eq $False){
Write-Error "ERROR: Line $(LINENUM): Unable to find information on LTSvc. Make sure the agent is installed."
Return $Null
}#End If
If ($PSCmdlet.ShouldProcess("LTService", "Retrieving Service Registry Values")) {
Write-Verbose "Checking for LT Service registry keys."
Try{
$key = Get-ItemProperty 'HKLM:\SOFTWARE\LabTech\Service' -ErrorAction Stop | Select-Object * -exclude $exclude
If ($Null -ne $key -and -not ($key|Get-Member -EA 0|Where-Object {$_.Name -match 'BasePath'})) {
If ((Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LTService') -eq $True) {
Try {
$BasePath = Get-Item $( Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Services\LTService' -ErrorAction Stop|Select-Object -Expand ImagePath | Select-String -Pattern '^[^"][^ ]+|(?<=^")[^"]+'|Select-Object -Expand Matches -First 1 | Select-Object -Expand Value -EA 0 -First 1 ) | Select-Object -Expand DirectoryName -EA 0
} Catch {
$BasePath = "${env:windir}\LTSVC"
}#End Try
} Else {
$BasePath = "${env:windir}\LTSVC"
}#End If
Add-Member -InputObject $key -MemberType NoteProperty -Name BasePath -Value $BasePath
}#End If
$key.BasePath = [System.Environment]::ExpandEnvironmentVariables($($key|Select-Object -Expand BasePath -EA 0)) -replace '\\\\','\'
If ($Null -ne $key -and ($key|Get-Member|Where-Object {$_.Name -match 'Server Address'})) {
$Servers = ($Key|Select-Object -Expand 'Server Address' -EA 0).Split('|')|ForEach-Object {$_.Trim() -replace '~',''}|Where-Object {$_ -match '.+'}
Add-Member -InputObject $key -MemberType NoteProperty -Name 'Server' -Value $Servers -Force
}#End If
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was a problem reading the registry keys. $($Error[0])"
}#End Catch
}#End If
}#End Process
End{
If ($?){
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
return $key
} Else {
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End If
}#End End
}#End Function Get-LTServiceInfo
Function Get-LTServiceSettings{
<#
.SYNOPSIS
This function will pull the registry data from HKLM:\SOFTWARE\LabTech\Service\Settings into an object.
.NOTES
Version: 1.1
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
.LINK
http://labtechconsulting.com
#>
[CmdletBinding()]
Param ()
Begin{
Write-Verbose "Checking for registry keys."
if ((Test-Path 'HKLM:\SOFTWARE\LabTech\Service\Settings') -eq $False){
Write-Error "ERROR: Unable to find LTSvc settings. Make sure the agent is installed."
}
$exclude = "PSParentPath","PSChildName","PSDrive","PSProvider","PSPath"
}#End Begin
Process{
Try{
Get-ItemProperty HKLM:\SOFTWARE\LabTech\Service\Settings -ErrorAction Stop | Select-Object * -exclude $exclude
}#End Try
Catch{
Write-Error "ERROR: There was a problem reading the registry keys. $($Error[0])"
}#End Catch
}#End Process
End{
if ($?){
$key
}
}#End End
}#End Function Get-LTServiceSettings
Function Restart-LTService{
<#
.SYNOPSIS
This function will restart the LabTech Services.
.NOTES
Version: 1.3
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 3/13/2018
Purpose/Change: Added additional debugging output, support for ShouldProcess (-Confirm, -WhatIf)
Update Date: 3/21/2018
Purpose/Change: Removed ErrorAction Override
.LINK
http://labtechconsulting.com
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param()
Begin{
Write-Debug "Starting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End Begin
Process{
if (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
If ($WhatIfPreference -ne $True) {
Write-Error "ERROR: Line $(LINENUM): Services NOT Found $($Error[0])"
return
} Else {
Write-Error "What-If: Line $(LINENUM): Stopping: Services NOT Found"
return
}#End If
}#End IF
Try{
Stop-LTService
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was an error stopping the services. $($Error[0])"
return
}#End Catch
Try{
Start-LTService
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was an error starting the services. $($Error[0])"
return
}#End Catch
}#End Process
End{
If ($WhatIfPreference -ne $True) {
If ($?) {Write-Output "Services Restarted successfully."}
Else {$Error[0]}
}#End If
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End End
}#End Function Restart-LTService
Function Stop-LTService{
<#
.SYNOPSIS
This function will stop the LabTech Services.
.DESCRIPTION
This function will verify that the LabTech services are present then attempt to stop them.
It will then check for any remaining LabTech processes and kill them.
.NOTES
Version: 1.3
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 3/12/2018
Purpose/Change: Updated Support for ShouldProcess to enable -Confirm and -WhatIf parameters.
Update Date: 3/21/2018
Purpose/Change: Removed ErrorAction Override
.LINK
http://labtechconsulting.com
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param()
Begin{
Clear-Variable sw,timeout,svcRun -EA 0 -WhatIf:$False -Confirm:$False -Verbose:$False #Clearing Variables for use
Write-Debug "Starting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End Begin
Process{
if (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
If ($WhatIfPreference -ne $True) {
Write-Error "ERROR: Line $(LINENUM): Services NOT Found $($Error[0])"
return
} Else {
Write-Error "What If: Line $(LINENUM): Stopping: Services NOT Found"
return
}#End If
}#End If
If ($PSCmdlet.ShouldProcess("LTService, LTSvcMon", "Stop-Service")) {
$Null=Invoke-LTServiceCommand ('Kill VNC','Kill Trays') -EA 0 -WhatIf:$False -Confirm:$False
Write-Verbose "Stopping Labtech Services"
Try{
('LTService','LTSvcMon') | Foreach-Object {
Try {$Null=& "${env:windir}\system32\sc.exe" stop "$($_)" 2>''}
Catch {Write-Output "Error calling sc.exe."}
}
$timeout = new-timespan -Minutes 1
$sw = [diagnostics.stopwatch]::StartNew()
Write-Host -NoNewline "Waiting for Services to Stop."
Do {
Write-Host -NoNewline '.'
Start-Sleep 2
$svcRun = ('LTService','LTSvcMon') | Get-Service -EA 0 | Where-Object {$_.Status -ne 'Stopped'} | Measure-Object | Select-Object -Expand Count
} Until ($sw.elapsed -gt $timeout -or $svcRun -eq 0)
Write-Host ""
$sw.Stop()
if ($svcRun -gt 0) {
Write-Verbose "Services did not stop. Terminating Processes after $(([int32]$sw.Elapsed.TotalSeconds).ToString()) seconds."
}
Get-Process | Where-Object {@('LTTray','LTSVC','LTSvcMon') -contains $_.ProcessName } | Stop-Process -Force -ErrorAction Stop -Whatif:$False -Confirm:$False
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was an error stopping the LabTech processes. $($Error[0])"
return
}#End Catch
}#End If
}#End Process
End{
If ($WhatIfPreference -ne $True) {
If ($?) {
If((('LTService','LTSvcMon') | Get-Service -EA 0 | Where-Object {$_.Status -ne 'Stopped'} | Measure-Object | Select-Object -Expand Count) -eq 0){
Write-Output "Services Stopped successfully."
} Else {
Write-Warning "WARNING: Line $(LINENUM): Services have not stopped completely."
}
} Else {$Error[0]}
}#End If
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End End
}#End Function Stop-LTService
Function Start-LTService{
<#
.SYNOPSIS
This function will start the LabTech Services.
.DESCRIPTION
This function will verify that the LabTech services are present.
It will then check for any process that is using the LTTray port (Default 42000) and kill it.
Next it will start the services.
.NOTES
Version: 1.5
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 5/11/2017
Purpose/Change: added check for non standard port number and set services to auto start
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 12/14/2017
Purpose/Change: Will increment the tray port if a conflict is detected.
Update Date: 2/1/2018
Purpose/Change: Added support for -WhatIf. Added Service Control Command to request agent check-in immediately after startup.
Update Date: 3/21/2018
Purpose/Change: Removed ErrorAction Override
.LINK
http://labtechconsulting.com
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param()
Begin{
Write-Debug "Starting $($myInvocation.InvocationName) at line $(LINENUM)"
#Identify processes that are using the tray port
[array]$processes = @()
$Port = (Get-LTServiceInfo -EA 0 -Verbose:$False -WhatIf:$False -Confirm:$False -Debug:$False|Select-Object -Expand TrayPort -EA 0)
if (-not ($Port)) {$Port = "42000"}
$startedSvcCount=0
}#End Begin
Process{
If (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
If ($WhatIfPreference -ne $True) {
Write-Error "ERROR: Line $(LINENUM): Services NOT Found $($Error[0])"
return
} Else {
Write-Error "What If: Line $(LINENUM): Stopping: Services NOT Found"
return
}#End If
}#End If
Try{
If((('LTService') | Get-Service -EA 0 | Where-Object {$_.Status -eq 'Stopped'} | Measure-Object | Select-Object -Expand Count) -gt 0) {
Try {$netstat=& "${env:windir}\system32\netstat.exe" -a -o -n 2>'' | Select-String -Pattern " .*[0-9\.]+:$($Port).*[0-9\.]+:[0-9]+ .*?([0-9]+)" -EA 0}
Catch {Write-Output "Error calling netstat.exe."; $netstat=$null}
Foreach ($line in $netstat){
$processes += ($line -split ' {4,}')[-1]
}#End Foreach
$processes = $processes | Where-Object {$_ -gt 0 -and $_ -match '^\d+$'}| Sort-Object | Get-Unique
If ($processes) {
Foreach ($proc in $processes){
Write-Output "Process ID:$proc is using port $Port. Killing process."
Try{Stop-Process -ID $proc -Force -Verbose -EA Stop}
Catch {
Write-Warning "WARNING: Line $(LINENUM): There was an issue killing the following process: $proc"
Write-Warning "WARNING: Line $(LINENUM): This generally means that a 'protected application' is using this port."
$newPort = [int]$port + 1
if($newPort -gt 42009) {$newPort = 42000}
Write-Warning "WARNING: Line $(LINENUM): Setting tray port to $newPort."
New-ItemProperty -Path "HKLM:\Software\Labtech\Service" -Name TrayPort -PropertyType String -Value $newPort -Force -WhatIf:$False -Confirm:$False | Out-Null
}#End Catch
}#End Foreach
}#End If
}#End If
If ($PSCmdlet.ShouldProcess("LTService, LTSvcMon", "Start Service")) {
@('LTService','LTSvcMon') | ForEach-Object {
If (Get-Service $_ -EA 0) {
Set-Service $_ -StartupType Automatic -EA 0 -Confirm:$False -WhatIf:$False
$Null=& "${env:windir}\system32\sc.exe" start "$($_)" 2>''
$startedSvcCount++
Write-Debug "Line $(LINENUM): Executed Start Service for $($_)"
}#End If
}#End ForEach-Object
}#End If
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was an error starting the LabTech services. $($Error[0])"
return
}#End Catch
}#End Process
End{
If ($WhatIfPreference -ne $True) {
If ($?){
$svcnotRunning = ('LTService') | Get-Service -EA 0 | Where-Object {$_.Status -ne 'Running'} | Measure-Object | Select-Object -Expand Count
If ($svcnotRunning -gt 0 -and $startedSvcCount -eq 2) {
$timeout = new-timespan -Minutes 1
$sw = [diagnostics.stopwatch]::StartNew()
Write-Host -NoNewline "Waiting for Services to Start."
Do {
Write-Host -NoNewline '.'
Start-Sleep 2
$svcnotRunning = ('LTService') | Get-Service -EA 0 | Where-Object {$_.Status -ne 'Running'} | Measure-Object | Select-Object -Expand Count
} Until ($sw.elapsed -gt $timeout -or $svcnotRunning -eq 0)
Write-Host ""
$sw.Stop()
}#End If
If ($svcnotRunning -eq 0) {
Write-Output "Services Started successfully."
$Null=Invoke-LTServiceCommand 'Send Status' -EA 0 -Confirm:$False
} ElseIf ($startedSvcCount -gt 0) {
Write-Output "Service Start was issued but LTService has not reached Running state."
} Else {
Write-Output "Service Start was not issued."
}#End If
}
Else{
$($Error[0])
}#End If
}#End If
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End End
}#End Function Start-LTService
Function Uninstall-LTService{
<#
.SYNOPSIS
This function will uninstall the LabTech agent from the machine.
.DESCRIPTION
This function will stop all the LabTech services. It will then download the current agent install MSI and issue an uninstall command.
It will then download and run Agent_Uninstall.exe from the LabTech server. It will then scrub any remaining file/registry/service data.
.PARAMETER Server
This is the URL to your LabTech server.
Example: https://lt.domain.com
This is used to download the uninstall utilities.
If no server is provided the uninstaller will use Get-LTServiceInfo to get the server address.
.PARAMETER Backup
This will run a 'New-LTServiceBackup' before uninstalling.
.PARAMETER Force
This will force operation on an agent detected as a probe.
.EXAMPLE
Uninstall-LTService
This will uninstall the LabTech agent using the server address in the registry.
.EXAMPLE
Uninstall-LTService -Server 'https://lt.domain.com'
This will uninstall the LabTech agent using the provided server URL to download the uninstallers.
.NOTES
Version: 1.9.1
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 6/10/2017
Purpose/Change: Updates for pipeline input, support for multiple servers
Update Date: 6/24/2017
Purpose/Change: Update to detect Server Version and use updated URL format for LabTech 11 Patch 13.
Update Date: 8/24/2017
Purpose/Change: Update to use Clear-Variable. Modifications to Folder and Registry Delete steps. Additional Debugging.
Update Date: 1/26/2017
Purpose/Change: Added support for Proxy Server for Download and Installation steps.
Update Date: 3/12/2018
Purpose/Change: Added detection of "Probe" enabled agent.
Added support for -Force parameter to override probe detection.
Updated support of -WhatIf parameter.
Added minimum size requirement for agent installer to detect and skip a bad file download.
Update Date: 10/18/2018
Purpose/Change: Added minimum size requirement for agent uninstaller exe to detect and skip a bad file download.
Uninstall will proceed even if the agent uninstaller exe cannot be downloaded.
Update Date: 1/21/2019
Purpose/Change: Minor bugfixes/adjustments.
Allow single label server name.
Update Date: 2/28/2019
Purpose/Change: Update to try both http and https method if not specified for Server
Update Date: 6/22/2020
Purpose/Change: Use unique pathname for Uninstall MSI, add Uninstaller EXE fallback
Update Date: 7/25/2024
Purpose/Change: Uninstaller EXE fallback even if server is unavailable
.LINK
http://labtechconsulting.com
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[AllowNull()]
[string[]]$Server,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[switch]$Backup,
[switch]$Force
)
Begin{
Clear-Variable Executables,BasePath,reg,regs,installer,installerTest,installerResult,LTSI,uninstaller,uninstallerTest,uninstallerResult,xarg,Svr,SVer,SvrVer,SvrVerCheck,GoodServer,AlternateServer,Item -EA 0 -WhatIf:$False -Confirm:$False #Clearing Variables for use
Write-Debug "Starting $($myInvocation.InvocationName) at line $(LINENUM)"
If (-not ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()|Select-Object -Expand groups -EA 0) -match 'S-1-5-32-544'))) {
Throw "Line $(LINENUM): Needs to be ran as Administrator"
}
$LTSI = Get-LTServiceInfo -EA 0 -Verbose:$False -WhatIf:$False -Confirm:$False -Debug:$False
If (($LTSI) -and ($LTSI|Select-Object -Expand Probe -EA 0) -eq '1') {
If ($Force -eq $True) {
Write-Output "Probe Agent Detected. UnInstall Forced."
} Else {
Write-Error -Exception [System.OperationCanceledException]"Line $(LINENUM): Probe Agent Detected. UnInstall Denied." -ErrorAction Stop
}#End If
}#End If
If ($Backup){
If ( $PSCmdlet.ShouldProcess("LTService","Backup Current Service Settings") ) {
New-LTServiceBackup
}#End If
}#End If
$BasePath = $(Get-LTServiceInfo -EA 0 -Verbose:$False -WhatIf:$False -Confirm:$False -Debug:$False|Select-Object -Expand BasePath -EA 0)
If (-not ($BasePath)) {$BasePath = "${env:windir}\LTSVC"}
$UninstallBase="${env:windir}\Temp"
$UninstallEXE='Agent_Uninstall.exe'
$UninstallMSI='RemoteAgent.msi'
New-PSDrive HKU Registry HKEY_USERS -ErrorAction SilentlyContinue -WhatIf:$False -Confirm:$False -Debug:$False| Out-Null
$regs = @( 'Registry::HKEY_LOCAL_MACHINE\Software\LabTechMSP',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\LabTech\Service',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\LabTech\LabVNC',
'Registry::HKEY_LOCAL_MACHINE\Software\Wow6432Node\LabTech\Service',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Managed\\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\D1003A85576B76D45A1AF09A0FC87FAC\InstallProperties',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{58A3001D-B675-4D67-A5A1-0FA9F08CF7CA}',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{3426921d-9ad5-4237-9145-f15dee7e3004}',
'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Appmgmt\{40bf8c82-ed0d-4f66-b73e-58a3d7ab6582}',
'Registry::HKEY_CLASSES_ROOT\Installer\Dependencies\{3426921d-9ad5-4237-9145-f15dee7e3004}',
'Registry::HKEY_CLASSES_ROOT\Installer\Dependencies\{3F460D4C-D217-46B4-80B6-B5ED50BD7CF5}',
'Registry::HKEY_CLASSES_ROOT\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
'Registry::HKEY_CLASSES_ROOT\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
'Registry::HKEY_CLASSES_ROOT\CLSID\{09DF1DCA-C076-498A-8370-AD6F878B6C6A}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{15DD3BF6-5A11-4407-8399-A19AC10C65D0}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{3C198C98-0E27-40E4-972C-FDC656EC30D7}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{459C65ED-AA9C-4CF1-9A24-7685505F919A}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{7BE3886B-0C12-4D87-AC0B-09A5CE4E6BD6}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{7E092B5C-795B-46BC-886A-DFFBBBC9A117}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{9D101D9C-18CC-4E78-8D78-389E48478FCA}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{B0B8CDD6-8AAA-4426-82E9-9455140124A1}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{B1B00A43-7A54-4A0F-B35D-B4334811FAA4}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{BBC521C8-2792-43FE-9C91-CCA7E8ACBCC9}',
'Registry::HKEY_CLASSES_ROOT\CLSID\{C59A1D54-8CD7-4795-AEDD-F6F6E2DE1FE7}',
'Registry::HKEY_CLASSES_ROOT\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
'Registry::HKEY_CLASSES_ROOT\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
'Registry::HKEY_CURRENT_USER\SOFTWARE\LabTech\Service',
'Registry::HKEY_CURRENT_USER\SOFTWARE\LabTech\LabVNC',
'Registry::HKEY_CURRENT_USER\Software\Microsoft\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
'HKU:\*\Software\Microsoft\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F'
)
$xarg = "/x ""$UninstallBase\$UninstallMSI"" /qn"
}#End Begin
Process{
If (-not ($Server)){
$Server = Get-LTServiceInfo -EA 0 -Verbose:$False -WhatIf:$False -Confirm:$False -Debug:$False|Select-Object -Expand 'Server' -EA 0
}
If (-not ($Server)){
$Server = Read-Host -Prompt 'Provide the URL to your LabTech server (https://lt.domain.com)'
}
$Server=ForEach ($Svr in $Server) {If (($Svr)) {If ($Svr -notmatch 'https?://.+') {"https://$($Svr)"}; $Svr}}
ForEach ($Svr in $Server) {
If (-not ($GoodServer)) {
If ($Svr -match '^(https?://)?(([12]?[0-9]{1,2}\.){3}[12]?[0-9]{1,2}|[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)*)$') {
Try{
If ($Svr -notmatch 'https?://.+') {$Svr = "http://$($Svr)"}
$SvrVerCheck = "$($Svr)/LabTech/Agent.aspx"
Write-Debug "Line $(LINENUM): Testing Server Response and Version: $SvrVerCheck"
$SvrVer = $Script:LTServiceNetWebClient.DownloadString($SvrVerCheck)
Write-Debug "Line $(LINENUM): Raw Response: $SvrVer"
$SVer = $SvrVer|select-string -pattern '(?<=[|]{6})[0-9]{1,3}\.[0-9]{1,3}'|ForEach-Object {$_.matches}|Select-Object -Expand value -EA 0
If ($Null -eq ($SVer)) {
Write-Verbose "Unable to test version response from $($Svr)."
Continue
}
$installer = "$($Svr)/LabTech/Service/LabTechRemoteAgent.msi"
$installerTest = [System.Net.WebRequest]::Create($installer)
If (($Script:LTProxy.Enabled) -eq $True) {
Write-Debug "Line $(LINENUM): Proxy Configuration Needed. Applying Proxy Settings to request."
$installerTest.Proxy=$Script:LTWebProxy
}#End If
$installerTest.KeepAlive=$False
$installerTest.ProtocolVersion = '1.0'
$installerResult = $installerTest.GetResponse()
$installerTest.Abort()
If ($installerResult.StatusCode -ne 200) {
Write-Warning "WARNING: Line $(LINENUM): Unable to download $UninstallMSI from server $($Svr)."
Continue
} Else {
If ($PSCmdlet.ShouldProcess("$installer", "DownloadFile")) {
Write-Debug "Line $(LINENUM): Downloading $UninstallMSI from $installer"
$Script:LTServiceNetWebClient.DownloadFile($installer,"$UninstallBase\$UninstallMSI")
If ((Test-Path "$UninstallBase\$UninstallMSI")) {
If (!((Get-Item "$UninstallBase\$UninstallMSI" -EA 0).length/1KB -gt 1234)) {
Write-Warning "WARNING: Line $(LINENUM): $UninstallMSI size is below normal. Removing suspected corrupt file."
Remove-Item "$UninstallBase\$UninstallMSI" -ErrorAction SilentlyContinue -Force -Confirm:$False
Continue
}#End If
}#End If
}#End If
}#End If
#Using $SVer results gathered above.
If ([System.Version]$SVer -ge [System.Version]'110.374') {
#New Style Download Link starting with LT11 Patch 13 - The Agent Uninstaller URI has changed.
$uninstaller = "$($Svr)/LabTech/Service/LabUninstall.exe"
} Else {
#Original Uninstaller URL
$uninstaller = "$($Svr)/LabTech/Service/LabUninstall.exe"
}
$uninstallerTest = [System.Net.WebRequest]::Create($uninstaller)
If (($Script:LTProxy.Enabled) -eq $True) {
Write-Debug "Line $(LINENUM): Proxy Configuration Needed. Applying Proxy Settings to request."
$uninstallerTest.Proxy=$Script:LTWebProxy
}#End If
$uninstallerTest.KeepAlive=$False
$uninstallerTest.ProtocolVersion = '1.0'
$uninstallerResult = $uninstallerTest.GetResponse()
$uninstallerTest.Abort()
If ($uninstallerResult.StatusCode -ne 200) {
Write-Warning "WARNING: Line $(LINENUM): Unable to download Agent_Uninstall from server."
Continue
} Else {
#Download $UninstallEXE
If ($PSCmdlet.ShouldProcess("$uninstaller", "DownloadFile")) {
Write-Debug "Line $(LINENUM): Downloading $UninstallEXE from $uninstaller"
$Script:LTServiceNetWebClient.DownloadFile($uninstaller,"$UninstallBase\$UninstallEXE")
If ((Test-Path "$UninstallBase\$UninstallEXE") -and !((Get-Item "$UninstallBase\$UninstallEXE" -EA 0).length/1KB -gt 80)) {
Write-Warning "WARNING: Line $(LINENUM): $UninstallEXE size is below normal. Removing suspected corrupt file."
Remove-Item "$UninstallBase\$UninstallEXE" -ErrorAction SilentlyContinue -Force -Confirm:$False
Continue
}#End If
}#End If
}#End If
If ($WhatIfPreference -eq $True) {
$GoodServer = $Svr
} ElseIf ((Test-Path "$UninstallBase\$UninstallMSI") -and (Test-Path "$UninstallBase\$UninstallEXE")) {
Write-Verbose "Successfully downloaded files from $($Svr)."
$GoodServer = $Svr
} Else {
Write-Warning "WARNING: Line $(LINENUM): Error encountered downloading from $($Svr). Uninstall file(s) could not be received."
Continue
}#End If
}#End Try
Catch {
Write-Warning "WARNING: Line $(LINENUM): Error encountered downloading from $($Svr)."
Continue
}
} ElseIf ($Svr) {
Write-Verbose "Server address $($Svr) is not formatted correctly. Example: https://lt.domain.com"
}#End If
} Else {
Write-Debug "Line $(LINENUM): Server $($GoodServer) has been selected."
Write-Verbose "Server has already been selected - Skipping $($Svr)."
}#End If
}#End Foreach
}#End Process
End{
If (-not ($GoodServer -match 'https?://.+')) {
#Download $UninstallEXE
$uninstaller='https://s3.amazonaws.com/assets-cp/assets/Agent_Uninstall.exe'
If ($PSCmdlet.ShouldProcess("$uninstaller", "DownloadFile")) {
Write-Debug "Line $(LINENUM): Downloading $UninstallEXE from $uninstaller"
$Script:LTServiceNetWebClient.DownloadFile($uninstaller,"$UninstallBase\$UninstallEXE")
If ((Test-Path "$UninstallBase\$UninstallEXE")) {
If(((Get-Item "$UninstallBase\$UninstallEXE" -EA 0).length/1KB -gt 80)) {
$GoodServer='https://s3.amazonaws.com'
} Else {
Write-Warning "Line $(LINENUM): $UninstallEXE size is below normal. Removing suspected corrupt file."
Remove-Item "$UninstallBase\$UninstallEXE" -ErrorAction SilentlyContinue -Force -Confirm:$False
}#End If
}#End If
}#End If
}
If ($GoodServer -match 'https?://.+') {
Try{
Write-Output "Starting Uninstall."
Try { Stop-LTService -ErrorAction SilentlyContinue } Catch {}
#Kill all running processes from %ltsvcdir%
If (Test-Path $BasePath){
$Executables = (Get-ChildItem $BasePath -Filter *.exe -Recurse -ErrorAction SilentlyContinue|Select-Object -Expand FullName)
If ($Executables) {
Write-Verbose "Terminating LabTech Processes from $($BasePath) if found running: $(($Executables) -replace [Regex]::Escape($BasePath),'' -replace '^\\','')"
Get-Process | Where-Object {$Executables -contains $_.Path } | ForEach-Object {
Write-Debug "Line $(LINENUM): Terminating Process $($_.ProcessName)"
$($_) | Stop-Process -Force -ErrorAction SilentlyContinue
}
Get-ChildItem $BasePath -Filter labvnc.exe -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction 0
}#End If
If ($PSCmdlet.ShouldProcess("$($BasePath)\wodVPN.dll", "Unregister DLL")) {
#Unregister DLL
Write-Debug "Line $(LINENUM): Executing Command ""regsvr32.exe /u $($BasePath)\wodVPN.dll /s"""
Try {& "${env:windir}\system32\regsvr32.exe" /u "$($BasePath)\wodVPN.dll" /s 2>''}
Catch {Write-Output "Error calling regsvr32.exe."}
}#End If
}#End If
If ($PSCmdlet.ShouldProcess("msiexec.exe $($xarg)", "Execute MSI Uninstall")) {
If ((Test-Path "$UninstallBase\$UninstallMSI")) {
#Run MSI uninstaller for current installation
Write-Verbose "Launching MSI Uninstall."
Write-Debug "Line $(LINENUM): Executing Command ""msiexec.exe $($xarg)"""
Start-Process -Wait -FilePath "${env:windir}\system32\msiexec.exe" -ArgumentList $xarg -WorkingDirectory $UninstallBase
Start-Sleep -Seconds 5
} Else {
Write-Verbose "WARNING: $UninstallBase\$UninstallMSI was not found."
}
}#End If
If ($PSCmdlet.ShouldProcess("$UninstallBase\$UninstallEXE", "Execute Agent Uninstall")) {
If ((Test-Path "$UninstallBase\$UninstallEXE")) {
#Run $UninstallEXE
Write-Verbose "Launching Agent Uninstaller"
Write-Debug "Line $(LINENUM): Executing Command ""$UninstallBase\$UninstallEXE"""
Start-Process -Wait -FilePath "$UninstallBase\$UninstallEXE" -WorkingDirectory $UninstallBase
Start-Sleep -Seconds 5
} Else {
Write-Verbose "WARNING: $UninstallBase\$UninstallEXE was not found."
}
}#End If
Write-Verbose "Removing Services if found."
#Remove Services
@('LTService','LTSvcMon','LabVNC') | ForEach-Object {
If (Get-Service $_ -EA 0) {
If ( $PSCmdlet.ShouldProcess("$($_)","Remove Service") ) {
Write-Debug "Line $(LINENUM): Removing Service: $($_)"
Try {& "${env:windir}\system32\sc.exe" delete "$($_)" 2>''}
Catch {Write-Output "Error calling sc.exe."}
}#End If
}#End If
}#End ForEach-Object
Write-Verbose "Cleaning Files remaining if found."
#Remove %ltsvcdir% - Depth First Removal, First by purging files, then Removing Folders, to get as much removed as possible if complete removal fails
@($BasePath, "${env:windir}\temp\_ltupdate", "${env:windir}\temp\_ltupdate") | foreach-object {
If ((Test-Path "$($_)" -EA 0)) {
If ( $PSCmdlet.ShouldProcess("$($_)","Remove Folder") ) {
Write-Debug "Line $(LINENUM): Removing Folder: $($_)"
Try {
Get-ChildItem -Path $_ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { ($_.psiscontainer) } | foreach-object { Get-ChildItem -Path "$($_.FullName)" -EA 0 | Where-Object { -not ($_.psiscontainer) } | Remove-Item -Force -ErrorAction SilentlyContinue -Confirm:$False -WhatIf:$False }
Get-ChildItem -Path $_ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { ($_.psiscontainer) } | Sort-Object { $_.fullname.length } -Descending | Remove-Item -Force -ErrorAction SilentlyContinue -Recurse -Confirm:$False -WhatIf:$False
Remove-Item -Recurse -Force -Path $_ -ErrorAction SilentlyContinue -Confirm:$False -WhatIf:$False
} Catch {}
}#End If
}#End If
}#End Foreach-Object
Write-Verbose "Cleaning Registry Keys if found."
#Remove all registry keys - Depth First Value Removal, then Key Removal, to get as much removed as possible if complete removal fails
Foreach ($reg in $regs) {
If ((Test-Path "$($reg)" -EA 0)) {
Write-Debug "Line $(LINENUM): Found Registry Key: $($reg)"
If ( $PSCmdlet.ShouldProcess("$($Reg)","Remove Registry Key") ) {
Try {
Get-ChildItem -Path $reg -Recurse -Force -ErrorAction SilentlyContinue | Sort-Object { $_.name.length } -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -Confirm:$False -WhatIf:$False
Remove-Item -Recurse -Force -Path $reg -ErrorAction SilentlyContinue -Confirm:$False -WhatIf:$False
} Catch {}
}#End If
}#End If
}#End Foreach
}#End Try
Catch{
Write-Error "ERROR: Line $(LINENUM): There was an error during the uninstall process. $($Error[0])" -ErrorAction Stop
}#End Catch
If ($WhatIfPreference -ne $True) {
If ($?){
#Post Uninstall Check
If((Test-Path "${env:windir}\ltsvc") -or (Test-Path "${env:windir}\temp\_ltupdate") -or (Test-Path registry::HKLM\Software\LabTech\Service) -or (Test-Path registry::HKLM\Software\WOW6432Node\Labtech\Service)){
Start-Sleep -Seconds 10
}#End If
If((Test-Path "${env:windir}\ltsvc") -or (Test-Path "${env:windir}\temp\_ltupdate") -or (Test-Path registry::HKLM\Software\LabTech\Service) -or (Test-Path registry::HKLM\Software\WOW6432Node\Labtech\Service)){
Write-Error "ERROR: Line $(LINENUM): Remnants of previous install still detected after uninstall attempt. Please reboot and try again."
} Else {
Write-Output "LabTech has been successfully uninstalled."
}#End If
} Else {
$($Error[0])
}#End If
}#End If
} ElseIf ($WhatIfPreference -ne $True) {
Write-Error "ERROR: Line $(LINENUM): No valid server was reached to use for the uninstall." -ErrorAction Stop
}#End If
If ($WhatIfPreference -ne $True) {
#Cleanup uninstall files
Remove-Item "$UninstallBase\$UninstallEXE","$UninstallBase\$UninstallMSI" -ErrorAction SilentlyContinue -Force -Confirm:$False
}#End If
Write-Debug "Exiting $($myInvocation.InvocationName) at line $(LINENUM)"
}#End End
}#End Function Uninstall-LTService
Function Install-LTService{
<#
.SYNOPSIS
This function will install the LabTech agent on the machine.
.DESCRIPTION
This function will install the LabTech agent on the machine with the specified server/password/location.
.PARAMETER Server
This is the URL to your LabTech server.
example: https://lt.domain.com
This is used to download the installation files.
(Get-LTServiceInfo|Select-Object -Expand 'Server Address' -ErrorAction SilentlyContinue)
.PARAMETER ServerPassword
This is the server password that agents use to authenticate with the LabTech server.
SELECT SystemPassword FROM config;
.PARAMETER InstallerToken
Permits use of installer tokens for customized MSI downloads. (Other installer types are not supported)
.PARAMETER LocationID
This is the LocationID of the location that the agent will be put into.
(Get-LTServiceInfo).LocationID
.PARAMETER TrayPort
This is the port LTSvc.exe listens on for communication with LTTray processes.
.PARAMETER Rename
This will call Rename-LTAddRemove after the install.
.PARAMETER Hide
This will call Hide-LTAddRemove after the install.
.PARAMETER SkipDotNet
This will disable the error checking for the .NET 3.5 and .NET 2.0 frameworks during the install process.
.PARAMETER Force
This will disable some of the error checking on the install process.
.PARAMETER NoWait
This will skip the ending health check for the install process.
The function will exit once the installer has completed.
.EXAMPLE
Install-LTService -Server https://lt.domain.com -Password 'plain text pass' -LocationID 42
This will install the LabTech agent using the provided Server URL, Password, and LocationID.
.NOTES
Version: 2.1
Author: Chris Taylor
Website: labtechconsulting.com
Creation Date: 3/14/2016
Purpose/Change: Initial script development
Update Date: 6/1/2017
Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
Update Date: 6/10/2017
Purpose/Change: Updates for pipeline input, support for multiple servers
Update Date: 6/24/2017
Purpose/Change: Update to detect Server Version and use updated URL format for LabTech 11 Patch 13.
Update Date: 8/24/2017
Purpose/Change: Update to use Clear-Variable. Additional Debugging.
Update Date: 8/29/2017