Advertisement
blackbinary

Untitled

Jan 24th, 2018
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. # look out for 8  lines containing "our.shitty.proxyprovider.tld"
  3.  
  4. # Script from https://raw.githubusercontent.com/LabtechConsulting/LabTech-Powershell-Module/master/LabTech.psm1
  5. # some changes for shitty.proxyprovider Proxy
  6.  
  7. if (-not ($PSVersionTable)) {Write-Warning 'PS1 Detected. PowerShell Version 2.0 or higher is required.';return}
  8. if (-not ($PSVersionTable) -or $PSVersionTable.PSVersion.Major -lt 3 ) {Write-Verbose 'PS2 Detected. PowerShell Version 3.0 or higher may be required for full functionality'}
  9. if (($ENV:PROCESSOR_ARCHITEW6432) -match '64' -and [IntPtr]::Size -ne 8) {Write-Warning '32-bit Session detected on 64-bit OS. Must run in native environment.';return}
  10.  
  11. #Module Version
  12. $ModuleVersion = "1.3"
  13.  
  14. #Ignore SSL errors
  15. add-type @"
  16.    using System.Net;
  17.    using System.Security.Cryptography.X509Certificates;
  18.    public class TrustAllCertsPolicy : ICertificatePolicy {
  19.        public bool CheckValidationResult(
  20.            ServicePoint srvPoint, X509Certificate certificate,
  21.            WebRequest request, int certificateProblem) {
  22.            return true;
  23.        }
  24.    }
  25. "@
  26. [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
  27.  
  28. #region-[Functions]------------------------------------------------------------
  29.  
  30. Function Get-LTServiceInfo{
  31. <#
  32. .SYNOPSIS
  33.     This function will pull all of the registry data into an object.
  34.  
  35. .NOTES
  36.     Version:        1.2
  37.     Author:         Chris Taylor
  38.     Website:        labtechconsulting.com
  39.     Creation Date:  3/14/2016
  40.     Purpose/Change: Initial script development
  41.  
  42.     Update Date: 6/1/2017
  43.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  44.    
  45.     Update Date: 8/24/2017
  46.     Purpose/Change: Update to use Clear-Variable.
  47.    
  48. .LINK
  49.     http://labtechconsulting.com
  50. #>
  51.     [CmdletBinding()]
  52.     Param ()
  53.      
  54.   Begin
  55.   {
  56.     Clear-Variable key,BasePath,exclude,Servers -EA 0 #Clearing Variables for use
  57.     Write-Verbose "Starting Get-LTServiceInfo"
  58.  
  59.     if ((Test-Path 'HKLM:\SOFTWARE\LabTech\Service') -eq $False){
  60.         Write-Error "ERROR: Unable to find information on LTSvc. Make sure the agent is installed."
  61.         Return
  62.     }
  63.     $exclude = "PSParentPath","PSChildName","PSDrive","PSProvider","PSPath"
  64.   }#End Begin
  65.  
  66.   Process{
  67.     Write-Verbose "Checking for LT Service registry keys."
  68.     Try{
  69.         $key = Get-ItemProperty HKLM:\SOFTWARE\LabTech\Service -ErrorAction Stop | Select * -exclude $exclude
  70.         if (-not ($key|Get-Member|Where {$_.Name -match 'BasePath'})) {
  71.                 if (Test-Path HKLM:\SYSTEM\CurrentControlSet\Services\LTService) {
  72.                         $BasePath = (Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Services\LTService -ErrorAction Stop|Select-object -Expand ImagePath -EA 0).Split('"')|Where {$_}|Select -First 1|Get-Item|Select-object -Expand DirectoryName -EA 0
  73.                     } Else {
  74.                         $BasePath = "$env:windir\LTSVC"
  75.                     }
  76.                     Add-Member -InputObject $key -MemberType NoteProperty -Name BasePath -Value $BasePath
  77.         }
  78.           $key.BasePath = [System.Environment]::ExpandEnvironmentVariables($($key|Select-object -Expand BasePath -EA 0))
  79.         if (($key|Get-Member|Where {$_.Name -match 'Server Address'})) {
  80.         $Servers = ($Key|Select-Object -Expand 'Server Address' -EA 0).Split('|')|Foreach {$_.Trim()}
  81.         Add-Member -InputObject $key -MemberType NoteProperty -Name 'Server' -Value $Servers -Force
  82.     }
  83.     }#End Try
  84.    
  85.     Catch{
  86.       Write-Error "ERROR: There was a problem reading the registry keys. $($Error[0])"
  87.     }#End Catch
  88.   }#End Process
  89.  
  90.   End{
  91.     if ($?){
  92.         $key
  93.     }    
  94.   }#End End
  95. }#End Function Get-LTServiceInfo
  96.  
  97. Function Get-LTServiceSettings{
  98. <#
  99. .SYNOPSIS
  100.     This function will pull the registry data from HKLM:\SOFTWARE\LabTech\Service\Settings into an object.
  101.  
  102. .NOTES
  103.     Version:        1.1
  104.     Author:         Chris Taylor
  105.     Website:        labtechconsulting.com
  106.     Creation Date:  3/14/2016
  107.     Purpose/Change: Initial script development
  108.  
  109.     Update Date: 6/1/2017
  110.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  111.    
  112. .LINK
  113.     http://labtechconsulting.com
  114. #>
  115.     [CmdletBinding()]
  116.     Param ()
  117.      
  118.   Begin{
  119.     Write-Verbose "Verbose: Checking for registry keys."
  120.     if ((Test-Path 'HKLM:\SOFTWARE\LabTech\Service\Settings') -eq $False){
  121.         Write-Error "ERROR: Unable to find LTSvc settings. Make sure the agent is installed." -ErrorAction Stop
  122.     }
  123.     $exclude = "PSParentPath","PSChildName","PSDrive","PSProvider","PSPath"
  124.   }#End Begin
  125.  
  126.   Process{
  127.     Try{
  128.         Get-ItemProperty HKLM:\SOFTWARE\LabTech\Service\Settings -ErrorAction Stop | Select * -exclude $exclude
  129.     }#End Try
  130.    
  131.     Catch{
  132.       Write-Error "ERROR: There was a problem reading the registry keys. $($Error[0])" -ErrorAction Stop
  133.     }#End Catch
  134.   }#End Process
  135.  
  136.   End{
  137.     if ($?){
  138.         $key
  139.     }    
  140.   }#End End
  141. }#End Function Get-LTServiceSettings
  142.  
  143. Function Restart-LTService{
  144. <#
  145. .SYNOPSIS
  146.     This function will restart the LabTech Services.
  147.  
  148. .NOTES
  149.     Version:        1.1
  150.     Author:         Chris Taylor
  151.     Website:        labtechconsulting.com
  152.     Creation Date:  3/14/2016
  153.     Purpose/Change: Initial script development
  154.  
  155.     Update Date: 6/1/2017
  156.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  157.    
  158. .LINK
  159.     http://labtechconsulting.com
  160. #>
  161.  
  162.     [CmdletBinding()]
  163.     Param()
  164.  
  165.   Begin{
  166.     if (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
  167.         Write-Error "ERROR: Services NOT Found $($Error[0])" -ErrorAction Stop
  168.     }
  169.   }#End Begin
  170.  
  171.   Process{
  172.     Try{
  173.       Stop-LTService
  174.       Start-LTService
  175.     }#End Try
  176.    
  177.     Catch{
  178.       Write-Error "ERROR: There was an error restarting the services. $($Error[0])" -ErrorAction Stop
  179.     }#End Catch
  180.   }#End Process
  181.  
  182.   End{
  183.     If ($?){Write-Output "Services Restarted successfully."}
  184.     Else {$Error[0]}
  185.   }#End End
  186. }#End Function Restart-LTService
  187.  
  188. Function Stop-LTService{
  189. <#
  190. .SYNOPSIS
  191.     This function will stop the LabTech Services.
  192.  
  193. .DESCRIPTION
  194.     This function will verify that the LabTech services are present then attempt to stop them.
  195.     It will then check for any remaining LabTech processes and kill them.
  196.  
  197. .NOTES
  198.     Version:        1.1
  199.     Author:         Chris Taylor
  200.     Website:        labtechconsulting.com
  201.     Creation Date:  3/14/2016
  202.     Purpose/Change: Initial script development
  203.  
  204.     Update Date: 6/1/2017
  205.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  206.    
  207. .LINK
  208.     http://labtechconsulting.com
  209. #>  
  210.     [CmdletBinding()]
  211.     Param()
  212.  
  213.     Begin{
  214.         Clear-Variable sw,timeout,svcRun -EA 0 #Clearing Variables for use
  215.         if (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
  216.             Write-Error "ERROR: Services NOT Found $($Error[0])" -ErrorAction Stop
  217.         }
  218.     }#End Begin
  219.  
  220.     Process{
  221.         Try{
  222.             Write-Verbose "Stopping Labtech Services"
  223.             ('LTService','LTSvcMon') | Stop-Service -ErrorAction SilentlyContinue
  224.             $timeout = new-timespan -Minutes 1
  225.             $sw = [diagnostics.stopwatch]::StartNew()
  226.             Write-Host -NoNewline "Waiting for Services to Stop."
  227.             Do {
  228.                 Write-Host -NoNewline '.'
  229.                 Start-Sleep 2
  230.                 $svcRun = ('LTService','LTSvcMon') | Get-Service -EA 0 | Where-Object {$_.Status -ne 'Stopped'} | Measure-Object | Select-Object -Expand Count
  231.             } until ($sw.elapsed -gt $timeout -or $svcRun -eq 0)
  232.             Write-Host ""
  233.             $sw.Stop()
  234.             if ($svcRun -gt 0) {
  235.                 Write-Verbose "Services did not stop. Terminating Processes after $([int32]$sw.Elapsed.TotalSeconds.ToString()) seconds."
  236.             }
  237.             Get-Process | Where-Object {@('LTTray','LTSVC','LTSvcMon') -contains $_.ProcessName } | Stop-Process -Force -ErrorAction Stop
  238.         }#End Try
  239.  
  240.         Catch{
  241.             Write-Error "ERROR: There was an error stopping the LabTech processes. $($Error[0])" -ErrorAction Stop
  242.         }#End Catch
  243.     }#End Process
  244.  
  245.     End{
  246.         If ($?){
  247.             Write-Output "Services Stopped successfully."
  248.         }
  249.         Else {$Error[0]}
  250.     }#End End
  251. }#End Function Stop-LTService
  252.  
  253. Function Start-LTService{
  254. <#
  255. .SYNOPSIS
  256.     This function will start the LabTech Services.
  257.  
  258. .DESCRIPTION
  259.     This function will verify that the LabTech services are present.
  260.     It will then check for any process that is using the LTTray port (Default 42000) and kill it.
  261.     Next it will start the services.
  262.  
  263. .NOTES
  264.     Version:        1.1
  265.     Author:         Chris Taylor
  266.     Website:        labtechconsulting.com
  267.     Creation Date:  3/14/2016
  268.     Purpose/Change: Initial script development
  269.  
  270.     Update Date: 5/11/2017
  271.     Purpose/Change: added check for non standard port number and set services to auto start
  272.  
  273.     Update Date: 6/1/2017
  274.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  275.  
  276.     Update Date: 12/14/2017
  277.     Purpose/Change: Will increment the tray port if a conflict is detected.
  278.        
  279. .LINK
  280.     http://labtechconsulting.com
  281. #>
  282.    
  283.     [CmdletBinding()]
  284.     Param()  
  285.    
  286.     Begin{
  287.         if (-not (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
  288.             Write-Error "ERROR: Services NOT Found $($Error[0])" -ErrorAction Stop
  289.         }
  290.         #Kill all processes that are using the tray port
  291.         [array]$processes = @()
  292.         $Port = (Get-LTServiceInfo -EA 0|Select-Object -Expand TrayPort -EA 0)
  293.         if (-not ($Port)) {$Port = "42000"}
  294.     }#End Begin
  295.    
  296.     Process{
  297.         Try{
  298.             $netstat = netstat.exe -a -o -n | Select-String -Pattern " .*[0-9\.]+:$($Port).*[0-9\.]+:[0-9]+ .*?([0-9]+)" -EA 0
  299.             foreach ($line in $netstat){
  300.                 $processes += ($line -split '  {3,}')[-1]
  301.             }
  302.             $processes = $processes | Where-Object {$_ -gt 0 -and $_ -match '^\d+$'}| Sort-Object | Get-Unique
  303.             if ($processes) {
  304.                     foreach ($proc in $processes){
  305.                     Write-Output "Process ID:$proc is using port $Port. Killing process."
  306.                     try{Stop-Process -ID $proc -Force -Verbose -EA Stop}
  307.                     catch {
  308.                         Write-Warning "There was an issue killing the following process: $proc"
  309.                         Write-Warning "This generally  means that a 'protected application' is using this port."
  310.                         $newPort = [int]$port + 1
  311.                         if($newPort > 42009) {$newPort = 42000}
  312.                         Write-Warning "Setting tray port to $newPort."
  313.                         New-ItemProperty -Path "HKLM:\Software\Labtech\Service" -Name TrayPort -PropertyType String -Value $newPort -Force | Out-Null
  314.                     }
  315.                 }
  316.             }
  317.             @('LTService','LTSvcMon') | ForEach-Object {
  318.                 if (Get-Service $_ -EA 0) {Set-Service $_ -StartupType Automatic -EA 0; Start-Service $_ -EA 0}
  319.             }
  320.         }#End Try
  321.    
  322.         Catch{
  323.             Write-Error "ERROR: There was an error starting the LabTech services. $($Error[0])" -ErrorAction Stop
  324.         }#End Catch
  325.     }#End Process
  326.    
  327.     End
  328.     {
  329.         If ($?){
  330.             Write-Output "Services Started successfully."
  331.         }
  332.         else{
  333.                 $($Error[0])
  334.         }
  335.     }#End End
  336. }#End Function Start-LTService
  337.  
  338. Function Uninstall-LTService{
  339. <#
  340. .SYNOPSIS
  341.     This function will uninstall the LabTech agent from the machine.
  342.  
  343. .DESCRIPTION
  344.     This function will stop all the LabTech services. It will then download the current agent install MSI and issue an uninstall command.
  345.     It will then download and run Agent_Uninstall.exe from the LabTech server. It will then scrub any remaining file/registry/service data.
  346.  
  347. .PARAMETER Server
  348.     This is the URL to your LabTech server.
  349.     Example: https://lt.domain.com
  350.     This is used to download the uninstall utilities.
  351.     If no server is provided the uninstaller will use Get-LTServiceInfo to get the server address.
  352.  
  353. .PARAMETER Backup
  354.     This will run a 'New-LTServiceBackup' before uninstalling.
  355.  
  356. .EXAMPLE
  357.     Uninstall-LTService
  358.     This will uninstall the LabTech agent using the server address in the registry.
  359.  
  360. .EXAMPLE
  361.     Uninstall-LTService -Server 'https://lt.domain.com'
  362.     This will uninstall the LabTech agent using the provided server URL to download the uninstallers.
  363.  
  364. .NOTES
  365.     Version:        1.4
  366.     Author:         Chris Taylor
  367.     Website:        labtechconsulting.com
  368.     Creation Date:  3/14/2016
  369.     Purpose/Change: Initial script development
  370.  
  371.     Update Date: 6/1/2017
  372.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  373.    
  374.     Update Date: 6/10/2017
  375.     Purpose/Change: Updates for pipeline input, support for multiple servers
  376.    
  377.     Update Date: 6/24/2017
  378.     Purpose/Change: Update to detect Server Version and use updated URL format for LabTech 11 Patch 13.
  379.    
  380.     Update Date: 8/24/2017
  381.     Purpose/Change: Update to use Clear-Variable. Modifications to Folder and Registry Delete steps. Additional Debugging.
  382.    
  383. .LINK
  384.     http://labtechconsulting.com
  385. #>
  386.     [CmdletBinding()]
  387.     Param(
  388.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  389.         [string[]]$Server,
  390.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  391.         [switch]$Backup = $False
  392.     )  
  393.     Begin{
  394.         Clear-Variable Executables,BasePath,reg,regs,installer,installerTest,installerResult,uninstaller,uninstallerTest,uninstallerResult,xarg,Svr,SVer,SvrVer,SvrVerCheck,GoodServer,Item -EA 0 #Clearing Variables for use
  395.         If (-not ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()|Select-object -Expand groups -EA 0) -match 'S-1-5-32-544'))) {
  396.             Throw "Needs to be ran as Administrator"
  397.         }
  398.         if ($Backup){
  399.             New-LTServiceBackup
  400.         }
  401.         $BasePath = $(Get-LTServiceInfo -EA 0|Select-Object -Expand BasePath -EA 0)
  402.         if (-not ($BasePath)){$BasePath = "$env:windir\LTSVC"}
  403.         New-PSDrive HKU Registry HKEY_USERS -ErrorAction SilentlyContinue | Out-Null
  404.         $regs = @( 'Registry::HKEY_LOCAL_MACHINE\Software\LabTechMSP',
  405.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\LabTech\Service',
  406.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\LabTech\LabVNC',
  407.             'Registry::HKEY_LOCAL_MACHINE\Software\Wow6432Node\LabTech\Service',
  408.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
  409.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
  410.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Managed\\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
  411.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\D1003A85576B76D45A1AF09A0FC87FAC\InstallProperties',
  412.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{58A3001D-B675-4D67-A5A1-0FA9F08CF7CA}',
  413.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\{3426921d-9ad5-4237-9145-f15dee7e3004}',
  414.             'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Appmgmt\{40bf8c82-ed0d-4f66-b73e-58a3d7ab6582}',
  415.             'Registry::HKEY_CLASSES_ROOT\Installer\Dependencies\{3426921d-9ad5-4237-9145-f15dee7e3004}',
  416.             'Registry::HKEY_CLASSES_ROOT\Installer\Dependencies\{3F460D4C-D217-46B4-80B6-B5ED50BD7CF5}',
  417.             'Registry::HKEY_CLASSES_ROOT\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
  418.             'Registry::HKEY_CLASSES_ROOT\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
  419.             'Registry::HKEY_CLASSES_ROOT\CLSID\{09DF1DCA-C076-498A-8370-AD6F878B6C6A}',
  420.             'Registry::HKEY_CLASSES_ROOT\CLSID\{15DD3BF6-5A11-4407-8399-A19AC10C65D0}',
  421.             'Registry::HKEY_CLASSES_ROOT\CLSID\{3C198C98-0E27-40E4-972C-FDC656EC30D7}',
  422.             'Registry::HKEY_CLASSES_ROOT\CLSID\{459C65ED-AA9C-4CF1-9A24-7685505F919A}',
  423.             'Registry::HKEY_CLASSES_ROOT\CLSID\{7BE3886B-0C12-4D87-AC0B-09A5CE4E6BD6}',
  424.             'Registry::HKEY_CLASSES_ROOT\CLSID\{7E092B5C-795B-46BC-886A-DFFBBBC9A117}',
  425.             'Registry::HKEY_CLASSES_ROOT\CLSID\{9D101D9C-18CC-4E78-8D78-389E48478FCA}',
  426.             'Registry::HKEY_CLASSES_ROOT\CLSID\{B0B8CDD6-8AAA-4426-82E9-9455140124A1}',
  427.             'Registry::HKEY_CLASSES_ROOT\CLSID\{B1B00A43-7A54-4A0F-B35D-B4334811FAA4}',
  428.             'Registry::HKEY_CLASSES_ROOT\CLSID\{BBC521C8-2792-43FE-9C91-CCA7E8ACBCC9}',
  429.             'Registry::HKEY_CLASSES_ROOT\CLSID\{C59A1D54-8CD7-4795-AEDD-F6F6E2DE1FE7}',
  430.             'Registry::HKEY_CLASSES_ROOT\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
  431.             'Registry::HKEY_CLASSES_ROOT\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC',
  432.             'Registry::HKEY_CURRENT_USER\SOFTWARE\LabTech\Service',
  433.             'Registry::HKEY_CURRENT_USER\SOFTWARE\LabTech\LabVNC',
  434.             'Registry::HKEY_CURRENT_USER\Software\Microsoft\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F',
  435.             'HKU:\*\Software\Microsoft\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F'
  436.         )
  437.  
  438.         #Cleanup previous uninstallers
  439.         Remove-Item 'Uninstall.exe','Uninstall.exe.config' -ErrorAction SilentlyContinue
  440.  
  441.         New-Item $env:windir\temp\LabTech\Installer -type directory -ErrorAction SilentlyContinue | Out-Null
  442.  
  443.         $xarg = "/x `"$($env:windir)\temp\LabTech\Installer\Agent_Install.msi`" /qn"
  444.     }#End Begin
  445.  
  446.     Process{
  447.         if (-not ($Server)){
  448.             $Server = Get-LTServiceInfo -ErrorAction SilentlyContinue|Select-Object -Expand 'Server' -EA 0
  449.         }
  450.         if (-not ($Server)){
  451.             $Server = Read-Host -Prompt 'Provide the URL to your LabTech server (https://lt.domain.com):'
  452.         }
  453.         Foreach ($Svr in $Server) {
  454.         if (-not ($GoodServer)) {
  455.                 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_-]*){1,})$') {
  456.                     Try{
  457.                         if ($Svr -notlike 'http*://*') {$Svr = "http://$($Svr)"}
  458.                         $SvrVerCheck = "$($Svr)/Labtech/Agent.aspx"
  459.                         Write-Debug "Testing Server Response and Version: $SvrVerCheck"
  460.                         # Changed by FUOG - Set system Proxy
  461.                         $wc=new-object net.webclient
  462.                         $wc.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  463.                         $SvrVer = $wc.DownloadString($SvrVerCheck)
  464.                         Write-Debug "Raw Response: $SvrVer"
  465.                         if ($SvrVer -NotMatch '(?<=[|]{6})[0-9]{3}\.[0-9]{3}') {
  466.                             Write-Verbose "Unable to test version response from $($Svr)."
  467.                             Continue
  468.                         }
  469.                         $SVer = $SvrVer|select-string -pattern '(?<=[|]{6})[0-9]{3}\.[0-9]{3}'|foreach {$_.matches}|select -Expand value
  470.                         if ([System.Version]$SVer -ge [System.Version]'110.374') {
  471.                             #New Style Download Link starting with LT11 Patch 13 - Direct Location Targeting is no longer available
  472.                             $installer = "$($Svr)/Labtech/Deployment.aspx?Probe=1&installType=msi&MSILocations=1"
  473.                         } else {
  474.                             #Original Generic Installer URL - Yes, these both reference Location 1 and are thus the same. Will it change in Patch 14? This section is now ready.
  475.                             $installer = "$($Svr)/Labtech/Deployment.aspx?Probe=1&installType=msi&MSILocations=1"
  476.                         }
  477.                         $installerTest = [System.Net.WebRequest]::Create($installer)
  478.                         $installerTest.KeepAlive=$False
  479.                         $installerTest.ProtocolVersion = '1.0'
  480.                         $installerTest.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  481.                         $installerResult = $installerTest.GetResponse()
  482.                         $installerTest.Abort()
  483.                         if ($installerResult.StatusCode -ne 200) {
  484.                             Write-Warning "Unable to download Agent_Install.msi from server $($Svr)."
  485.                             Continue
  486.                         }
  487.                         else{
  488.                             Write-Debug "Downloading Agent_Install.msi from $installer"
  489.                             # Changed by FUOG -- Set system Proxy
  490.                             $wc=new-object net.webclient
  491.                             $wc.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  492.                             $wc.DownloadFile($installer,"$env:windir\temp\LabTech\Installer\Agent_Install.msi")
  493.                         }
  494.  
  495.                         #Using $SVer results gathered above.
  496.                         if ([System.Version]$SVer -ge [System.Version]'110.374') {
  497.                             #New Style Download Link starting with LT11 Patch 13 - The Agent Uninstaller URI has changed.
  498.                             $uninstaller = "$($Svr)/Labtech/Deployment.aspx?ID=-2"
  499.                         } else {
  500.                             #Original Uninstaller URL
  501.                             $uninstaller = "$($Svr)/Labtech/Deployment.aspx?probe=1&ID=-2"
  502.                         }
  503.                         $uninstallerTest = [System.Net.WebRequest]::Create($uninstaller)
  504.                         $uninstallerTest.KeepAlive=$False
  505.                         $uninstallerTest.ProtocolVersion = '1.0'
  506.                         $uninstallerTest.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  507.                         $uninstallerResult = $uninstallerTest.GetResponse()
  508.                         $uninstallerTest.Abort()
  509.                         if ($uninstallerResult.StatusCode -ne 200) {
  510.                             Write-Warning "Unable to download Agent_Uninstall from server."
  511.                             Continue
  512.                         }
  513.                         else{
  514.                             Write-Debug "Downloading Agent_Uninstall.exe from $uninstaller"
  515.                             #Download Agent_Uninstall.exe
  516.                             #Changed by FUOG -- Set system Proxy
  517.                             $wc=new-object net.webclient
  518.                             $wc.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  519.                             $wc.DownloadFile($uninstaller,"$($env:windir)\temp\Agent_Uninstall.exe")
  520.                         }
  521.                         If ((Test-Path "$env:windir\temp\LabTech\Installer\Agent_Install.msi") -and (Test-Path "$($env:windir)\temp\Agent_Uninstall.exe")) {
  522.                             $GoodServer = $Svr
  523.                             Write-Verbose "Successfully downloaded files from $($Svr)."
  524.                         } else {
  525.                             Write-Warning "Error encountered downloading from $($Svr). Uninstall file(s) could be received."
  526.                             Continue
  527.                         }
  528.                     }
  529.                     Catch {
  530.                         Write-Warning "Error encountered downloading from $($Svr)."
  531.                         Continue
  532.                     }
  533.                 } else {
  534.                     Write-Verbose "Server address $($Svr) is not formatted correctly. Example: https://lt.domain.com"
  535.                 }
  536.             } else {
  537.                 Write-Debug "Server $($GoodServer) has been selected."
  538.                 Write-Verbose "Server has already been selected - Skipping $($Svr)."
  539.             }
  540.         }#End Foreach
  541.     }#End Process
  542.  
  543.     End{
  544.     $GoodServer
  545.         if ($GoodServer) {
  546.             Try{
  547.                 Write-Output "Starting Uninstall."
  548.  
  549.                 try { Stop-LTService -ErrorAction SilentlyContinue } catch {}
  550.                
  551.                 #Kill all running processes from %ltsvcdir%  
  552.                 if (Test-Path $BasePath){
  553.                     $Executables = (Get-ChildItem $BasePath -Filter *.exe -Recurse -ErrorAction SilentlyContinue|Select -Expand Name|Foreach {$_.Trim('.exe')})
  554.                     if ($Executables) {
  555.                         Write-Verbose "Terminating LabTech Processes if found running: $($Executables)"
  556.                         Get-Process | Where-Object {$Executables -contains $_.ProcessName } | ForEach-Object {
  557.                             Write-Debug "Terminating Process $($_.ProcessName)"
  558.                             $($_) | Stop-Process -Force -ErrorAction SilentlyContinue
  559.                         }
  560.                     }
  561.  
  562.                     #Unregister DLL
  563.                     regsvr32.exe /u $BasePath\wodVPN.dll /s 2>''
  564.                 }#End If    
  565.  
  566.                 If ((Test-Path "$($env:windir)\temp\LabTech\Installer\Agent_Install.msi")) {
  567.                     #Run MSI uninstaller for current installer
  568.                     Write-Verbose "Launching Uninstall: msiexec.exe $($xarg)"
  569.                     Start-Process -Wait -FilePath msiexec.exe -ArgumentList $xarg
  570.                     Start-Sleep -Seconds 5
  571.                 } else {
  572.                     Write-Verbose "WARNING: $($env:windir)\temp\LabTech\Installer\Agent_Install.msi was not found."
  573.                 }
  574.  
  575.                 If ((Test-Path "$($env:windir)\temp\Agent_Uninstall.exe")) {
  576.                     #Run Agent_Uninstall.exe
  577.                     Write-Verbose "Launching $($env:windir)\temp\Agent_Uninstall.exe"
  578.                     Start-Process -Wait -FilePath "$($env:windir)\temp\Agent_Uninstall.exe"
  579.                     Start-Sleep -Seconds 5
  580.                 } else {
  581.                     Write-Verbose "WARNING: $($env:windir)\temp\Agent_Uninstall.exe was not found."
  582.                 }
  583.  
  584.                 Write-Verbose "Removing Services if found."
  585.                 #Remove Services
  586.                 @('LTService','LTSvcMon') | ForEach-Object {
  587.                     if (Get-Service $_ -EA 0) {
  588.                         Write-Debug "Removing Service: $($_)"
  589.                         Start-Process -FilePath sc.exe -ArgumentList "delete $_" -Wait
  590.                     }
  591.                 }
  592.  
  593.                 Write-Verbose "Cleaning Files remaining if found."
  594.                 #Remove %ltsvcdir% - Depth First Removal, First by purging files, then Removing Folders, to get as much removed as possible if complete removal fails
  595.                 @($BasePath, "$($env:windir)\temp\_ltupdate", "$($env:windir)\temp\_ltudpate") | foreach-object {
  596.                     If ((Test-Path "$($_)" -EA 0)) {
  597.                         Write-Debug "Removing Item: $($_)"
  598.                         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 }
  599.                         Get-ChildItem -Path $_ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { ($_.psiscontainer) } | Sort-Object { $_.fullname.length } -Descending | Remove-Item -Force -ErrorAction SilentlyContinue -Recurse
  600.                         Remove-Item -Recurse -Force -Path $_ -ErrorAction SilentlyContinue
  601.                     }
  602.                 }
  603.  
  604.                 Write-Verbose "Cleaning Registry Keys if found."
  605.                 #Remove all registry keys - Depth First Value Removal, then Key Removal, to get as much removed as possible if complete removal fails
  606.                 foreach ($reg in $regs) {
  607.                     If ((Test-Path "$($reg)" -EA 0)) {
  608.                         Write-Debug "Removing Item: $($reg)"
  609.                         Get-ChildItem -Path $reg -Recurse -Force -ErrorAction SilentlyContinue | Sort-Object { $_.name.length } -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
  610.                         Remove-Item -Recurse -Force -Path $reg -ErrorAction SilentlyContinue
  611.                     }
  612.                 }
  613.                
  614.                 #Post Uninstall Check
  615.                 if((Test-Path $env:windir\ltsvc) -or (Test-Path $env:windir\temp\_ltudpate) -or (Test-Path registry::HKLM\Software\LabTech\Service) -or (Test-Path registry::HKLM\Software\WOW6432Node\Labtech\Service)){
  616.                     Start-Sleep -Seconds 10
  617.                 }
  618.                 if((Test-Path $env:windir\ltsvc) -or (Test-Path $env:windir\temp\_ltudpate) -or (Test-Path registry::HKLM\Software\LabTech\Service) -or (Test-Path registry::HKLM\Software\WOW6432Node\Labtech\Service)){
  619.                     Write-Error "Remnants of previous install still detected after uninstall attempt. Please reboot and try again."
  620.                 }
  621.  
  622.             }#End Try
  623.    
  624.             Catch{
  625.                 Write-Error "ERROR: There was an error during the uninstall process. $($Error[0])" -ErrorAction Stop
  626.             }#End Catch
  627.             If ($?){
  628.                 Write-Output "LabTech has been successfully uninstalled."
  629.             }
  630.             else {
  631.                 $($Error[0])
  632.             }
  633.         } else {
  634.             Write-Error "ERROR: No valid server was reached to use for the uninstall." -ErrorAction Stop
  635.         }#End If
  636.     }#End End
  637. }#End Function Uninstall-LTService
  638.  
  639. Function Install-LTService{
  640. <#
  641. .SYNOPSIS
  642.     This function will install the LabTech agent on the machine.
  643.  
  644. .DESCRIPTION
  645.     This function will install the LabTech agent on the machine with the specified server/password/location.
  646.  
  647. .PARAMETER Server
  648.     This is the URL to your LabTech server.
  649.     example: https://lt.domain.com
  650.     This is used to download the installation files.
  651.     (Get-LTServiceInfo|Select-Object -Expand 'Server Address' -ErrorAction SilentlyContinue)
  652.  
  653. .PARAMETER Password
  654.     This is the server password that agents use to authenticate with the LabTech server.
  655.     (Get-LTServiceInfo).ServerPassword
  656.  
  657. .PARAMETER LocationID
  658.     This is the LocationID of the location that the agent will be put into.
  659.     (Get-LTServiceInfo).LocationID
  660.  
  661. .PARAMETER Rename
  662.     This will call Rename-LTAddRemove after the install.
  663.  
  664. .PARAMETER Hide
  665.     This will call Hide-LTAddRemove after the install.
  666.  
  667. .PATAMETER Force
  668.     This will disable some of the error checking on the install process.
  669.  
  670. .EXAMPLE
  671.     Install-LTService -Server https://lt.domain.com -Password sQWZzEDYKFFnTT0yP56vgA== -LocationID 42
  672.     This will install the LabTech agent using the provided Server URL, Password, and LocationID.
  673.  
  674. .NOTES
  675.     Version:        1.6
  676.     Author:         Chris Taylor
  677.     Website:        labtechconsulting.com
  678.     Creation Date:  3/14/2016
  679.     Purpose/Change: Initial script development
  680.  
  681.     Update Date: 6/1/2017
  682.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  683.    
  684.     Update Date: 6/10/2017
  685.     Purpose/Change: Updates for pipeline input, support for multiple servers
  686.    
  687.     Update Date: 6/24/2017
  688.     Purpose/Change: Update to detect Server Version and use updated URL format for LabTech 11 Patch 13.
  689.  
  690.     Update Date: 8/24/2017
  691.     Purpose/Change: Update to use Clear-Variable. Additional Debugging.
  692.    
  693.     Update Date: 8/29/2017
  694.     Purpose/Change: Additional Debugging.
  695.    
  696.     Update Date: 9/7/2017
  697.     Purpose/Change: Support for ShouldProcess to enable -Confirm and -WhatIf.
  698.    
  699. .LINK
  700.     http://labtechconsulting.com
  701. #>
  702.     [CmdletBinding()]
  703.     Param(
  704.         [Parameter(ValueFromPipelineByPropertyName = $true, Mandatory=$True)]
  705.         [string[]]$Server,
  706.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  707.         [Alias("Password")]
  708.         [string]$ServerPassword,
  709.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  710.         [int]$LocationID,
  711.         [string]$Rename = $null,
  712.         [switch]$Hide = $False,
  713.         [switch]$Force = $False
  714.     )
  715.  
  716.     Begin{
  717.         Clear-Variable DotNET,OSVersion,PasswordArg,Result,logpath,logfile,curlog,installer,installerTest,installerResult,GoodServer,Svr,SVer,SvrVer,SvrVerCheck,iarg,timeout,sw,tmpLTSI -EA 0 #Clearing Variables for use
  718.  
  719.         if (!($Force)) {
  720.             if (Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue) {
  721.                 Write-Error "LabTech is already installed." -ErrorAction Stop
  722.             }
  723.  
  724.             If (-not ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()|Select-object -Expand Groups -EA 0) -match "S-1-5-32-544"))) {
  725.                 Write-Error "Needs to be ran as Administrator" -ErrorAction Stop
  726.             }
  727.         }
  728.  
  729.         $DotNET = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse -EA 0 | Get-ItemProperty -name Version,Release -EA 0 | Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} | Select-Object -ExpandProperty Version -EA 0
  730.         if (-not ($DotNet -like '3.5.*'))
  731.         {
  732.             Write-Output ".NET 3.5 installation needed."
  733.             #Install-WindowsFeature Net-Framework-Core
  734.             $OSVersion = [System.Environment]::OSVersion.Version
  735.  
  736.             if ([version]$OSVersion -gt [version]'6.2'){
  737.                 try{
  738.                     $Install = Enable-WindowsOptionalFeature -Online -FeatureName "NetFx3" -All
  739.                     if ($Install.RestartNeeded) {
  740.                         Write-Output ".NET 3.5 installed but a reboot is needed."
  741.                     }
  742.                 }
  743.                 catch{
  744.                     Write-Error "ERROR: .NET 3.5 install failed." -ErrorAction Continue
  745.                     if (!($Force)) { Write-Error $Install -ErrorAction Stop }
  746.                 }
  747.             }
  748.             else{
  749.                 $Result = Dism.exe /online /get-featureinfo /featurename:NetFx3 2>''
  750.                 If ($Result -contains "State : Enabled"){
  751.                     # also check reboot status, unsure of possible outputs
  752.                     # Restart Required : Possible
  753.  
  754.                     Write-Warning ".Net Framework 3.5 has been installed and enabled."
  755.                 }
  756.                 Else {
  757.                     Write-Error "ERROR: .NET 3.5 install failed." -ErrorAction Continue
  758.                     if (!($Force)) { Write-Error $Result -ErrorAction Stop }
  759.                 }
  760.             }
  761.            
  762.             $DotNET = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | Get-ItemProperty -name Version,Release -EA 0 | Where-Object{ $_.PSChildName -match '^(?!S)\p{L}'} | Select -ExpandProperty Version
  763.         }
  764.  
  765.         if (-not ($DotNet -like '3.5.*')){
  766.             if (($Force)) {
  767.                 if ($DotNet -like '2.0.*'){
  768.                     Write-Error "ERROR: .NET 3.5 is not detected and could not be installed." -ErrorAction Continue
  769.                 }
  770.                 Else {
  771.                     Write-Error "ERROR: .NET 2.0 is not detected and could not be installed." -ErrorAction Stop
  772.                 }
  773.             }
  774.             else {
  775.                 Write-Error "ERROR: .NET 3.5 is not detected and could not be installed." -ErrorAction Stop            
  776.             }
  777.         }
  778.         if (-not ($LocationID)){
  779.             $LocationID = "1"
  780.         }
  781.  
  782.         $logpath = [System.Environment]::ExpandEnvironmentVariables("%windir%\temp\LabTech")
  783.         $logfile = "LTAgentInstall"
  784.         $curlog = "$($logpath)\$($logfile).log"
  785.         if (-not (Test-Path -PathType Container -Path "$logpath\Installer" )){
  786.             New-Item "$logpath\Installer" -type directory -ErrorAction SilentlyContinue | Out-Null
  787.         }#End if
  788.         if ((Test-Path -PathType Leaf -Path $($curlog))){
  789.             $curlog = Get-Item -Path $curlog -EA 0
  790.             Rename-Item -Path $($curlog|Select-Object -Expand FullName -EA 0) -NewName "$($logfile)-$(Get-Date $($curlog|Select-Object -Expand LastWriteTime -EA 0) -Format 'yyyyMMddHHmmss').log" -Force
  791.             Remove-Item -Path $($curlog|Select-Object -Expand FullName -EA 0) -Force -EA 0
  792.         }#End if
  793.     }#End Begin
  794.  
  795.     Process{
  796.         Foreach ($Svr in $Server) {
  797.             if (-not ($GoodServer)) {
  798.                 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_-]*){1,})$') {
  799.                     if ($Svr -notlike 'http*://*') {$Svr = "http://$($Svr)"}
  800.                     Try {
  801.                         $SvrVerCheck = "$($Svr)/Labtech/Agent.aspx"
  802.                         Write-Debug "Testing Server Response and Version: $SvrVerCheck"
  803.                         # Changed by FUOG -- Set system Proxy
  804.                         $wc=new-object net.webclient
  805.                         $wc.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  806.                         $SvrVer = $wc.DownloadString($SvrVerCheck)
  807.                         Write-Debug "Raw Response: $SvrVer"
  808.                         if ($SvrVer -NotMatch '(?<=[|]{6})[0-9]{3}\.[0-9]{3}') {
  809.                             Write-Verbose "Unable to test version response from $($Svr)."
  810.                             Continue
  811.                         }
  812.                         $SVer = $SvrVer|select-string -pattern '(?<=[|]{6})[0-9]{3}\.[0-9]{3}'|foreach {$_.matches}|select -Expand value
  813.                         if ([System.Version]$SVer -ge [System.Version]'110.374') {
  814.                             #New Style Download Link starting with LT11 Patch 13 - Direct Location Targeting is no longer available
  815.                             $installer = "$($Svr)/Labtech/Deployment.aspx?Probe=1&installType=msi&MSILocations=1"
  816.                         } else {
  817.                             #Original URL
  818.                             $installer = "$($Svr)/Labtech/Deployment.aspx?Probe=1&installType=msi&MSILocations=$LocationID"
  819.                         }
  820.                         $installerTest = [System.Net.WebRequest]::Create($installer)
  821.                         $installerTest.KeepAlive=$False
  822.                         $installerTest.ProtocolVersion = '1.0'
  823.                         $installerTest.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  824.                         $installerResult = $installerTest.GetResponse()
  825.                         $installerTest.Abort()
  826.                         if ($installerResult.StatusCode -ne 200) {
  827.                             Write-Warning "Unable to download Agent_Install from server $($Svr)."
  828.                             Continue
  829.                         } else {
  830.                             Write-Debug "Downloading Agent_Install.msi from $installer"
  831.                             $wc=new-object net.webclient
  832.                             $wc.Proxy=new-object system.net.WebProxy('our.shitty.proxyprovider.tld:8880',$true)
  833.                             $wc.DownloadFile($installer,"$env:windir\temp\LabTech\Installer\Agent_Install.msi")
  834.                             If (Test-Path "$env:windir\temp\LabTech\Installer\Agent_Install.msi") {
  835.                                 $GoodServer = $Svr
  836.                                 Write-Verbose "Agent_Install.msi downloaded successfully from server $($Svr)."
  837.                             } else {
  838.                                 Write-Warning "Error encountered downloading from $($Svr). No installation file was received."
  839.                                 Continue
  840.                             }
  841.                         }
  842.                     }
  843.                     Catch {
  844.                         Write-Warning "Error encountered downloading from $($Svr)."
  845.                         Continue
  846.                     }
  847.                 } else {
  848.                     Write-Warning "Server address $($Svr) is not formatted correctly. Example: https://lt.domain.com"
  849.                 }
  850.             } else {
  851.                 Write-Debug "Server $($GoodServer) has been selected."
  852.                 Write-Verbose "Server has already been selected - Skipping $($Svr)."
  853.             }
  854.         }#End Foreach
  855.     }#End Process
  856.  
  857.     End{
  858.         if (($ServerPassword)){
  859.             $PasswordArg = "SERVERPASS=$ServerPassword"
  860.         }
  861.         if ($GoodServer) {
  862.             if((Test-Path "$($env:windir)\ltsvc" -EA 0) -or (Test-Path "$($env:windir)\temp\_ltudpate" -EA 0) -or (Test-Path registry::HKLM\Software\LabTech\Service -EA 0) -or (Test-Path registry::HKLM\Software\WOW6432Node\Labtech\Service -EA 0)){
  863.                 Write-Warning "Previous install detected. Calling Uninstall-LTService"
  864.                 Uninstall-LTService -Server $GoodServer
  865.                 Start-Sleep 10
  866.             }
  867.  
  868.             Write-Output "Starting Install."
  869.             $iarg = "/i  $env:windir\temp\LabTech\Installer\Agent_Install.msi SERVERADDRESS=$GoodServer $PasswordArg LOCATION=$LocationID /qn /l $logpath\$logfile.log"
  870.  
  871.             Try{
  872.                 Write-Verbose "Launching Installation Process: msiexec.exe $(($iarg))"
  873.                 Start-Process -Wait -FilePath msiexec.exe -ArgumentList $iarg
  874.                 $timeout = new-timespan -Minutes 3
  875.                 $sw = [diagnostics.stopwatch]::StartNew()
  876.                 Write-Host -NoNewline "Waiting for agent to register."
  877.                 Do {
  878.                     Write-Host -NoNewline '.'
  879.                     Start-Sleep 2
  880.                     $tmpLTSI = (Get-LTServiceInfo -EA 0 -Verbose:$False | Select-Object -Expand 'ID' -EA 0)
  881.                 } until ($sw.elapsed -gt $timeout -or $tmpLTSI -gt 1)
  882.                 $sw.Stop()
  883.                 Write-Verbose "Completed wait for LabTech Installation after $([int32]$sw.Elapsed.TotalSeconds.ToString()) seconds."
  884.                 If ($Hide) {Hide-LTAddRemove}
  885.             }#End Try
  886.  
  887.             Catch{
  888.                 Write-Error "ERROR: There was an error during the install process. $($Error[0])" -ErrorAction Stop
  889.             }#End Catch
  890.  
  891.             $tmpLTSI = Get-LTServiceInfo -EA 0
  892.             if (($tmpLTSI)) {
  893.                 if (($tmpLTSI|Select-Object -Expand 'ID' -EA 0) -gt 1) {
  894.                     Write-Host ""
  895.                     Write-Output "LabTech has been installed successfully. Agent ID: $($tmpLTSI|Select-Object -Expand 'ID' -EA 0) LocationID: $($tmpLTSI|Select-Object -Expand 'LocationID' -EA 0)"
  896.                     if (($Rename) -and $Rename -notmatch 'False'){
  897.                         Rename-LTAddRemove -Name $Rename
  898.                     }
  899.                 }
  900.             }
  901.             else {
  902.                 if (($Error)) {
  903.                     Write-Error "ERROR: There was an error installing LabTech. Check the log, $($env:windir)\temp\LabTech\LTAgentInstall.log $($Error[0])" -ErrorAction Stop
  904.                 } else {
  905.                     Write-Error "ERROR: There was an error installing LabTech. Check the log, $($env:windir)\temp\LabTech\LTAgentInstall.log" -ErrorAction Stop
  906.                 }
  907.             }
  908.         } else {
  909.             Write-Error "ERROR: No valid server was reached to use for the install." -ErrorAction Stop
  910.         }
  911.     }#End End
  912. }#End Function Install-LTService
  913.  
  914. Function Reinstall-LTService{
  915. <#
  916. .SYNOPSIS
  917.     This function will reinstall the LabTech agent from the machine.
  918.  
  919. .DESCRIPTION
  920.     This script will attempt to pull all current settings from machine and issue an 'Uninstall-LTService', 'Install-LTService' with gathered information.
  921.     If the function is unable to find the settings it will ask for needed parameters.
  922.  
  923. .PARAMETER Server
  924.     This is the URL to your LabTech server.
  925.     Example: https://lt.domain.com
  926.     This is used to download the installation and removal utilities.
  927.     If no server is provided the uninstaller will use Get-LTServiceInfo to get the server address.
  928.     If it is unable to find LT currently installed it will try Get-LTServiceInfoBackup
  929.  
  930. .PARAMETER Password
  931.     This is the Server Password to your LabTech server.
  932.     example: sRWyzEF0KaFzHTnyP56vgA==
  933.     You can find this from a configured agent with, '(Get-LTServiceInfo).ServerPassword'
  934.    
  935. .PARAMETER LocationID
  936.     The LocationID of the location that you want the agent in
  937.     example: 555
  938.  
  939. .PARAMETER Backup
  940.     This will run a New-LTServiceBackup command before uninstalling.
  941.  
  942. .PARAMETER Hide
  943.     Will remove from add-remove programs
  944.  
  945. .PARAMETER Rename
  946.     This will call Rename-LTAddRemove to rename the install in Add/Remove Programs
  947.  
  948. .EXAMPLE
  949.     ReInstall-LTService
  950.     This will ReInstall the LabTech agent using the server address in the registry.
  951.  
  952. .EXAMPLE
  953.     ReInstall-LTService -Server https://lt.domain.com -Password sQWZzEDYKFFnTT0yP56vgA== -LocationID 42
  954.     This will ReInstall the LabTech agent using the provided server URL to download the installation files.
  955.  
  956. .NOTES
  957.     Version:        1.4
  958.     Author:         Chris Taylor
  959.     Website:        labtechconsulting.com
  960.     Creation Date:  3/14/2016
  961.     Purpose/Change: Initial script development
  962.  
  963.     Update Date: 6/1/2017
  964.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  965.    
  966.     Update Date: 6/8/2017
  967.     Purpose/Change: Update to support user provided settings for -Server, -Password, -LocationID.
  968.    
  969.     Update Date: 6/10/2017
  970.     Purpose/Change: Updates for pipeline input, support for multiple servers
  971.    
  972.     Update Date: 8/24/2017
  973.     Purpose/Change: Update to use Clear-Variable.
  974.    
  975. .LINK
  976.     http://labtechconsulting.com
  977. #>
  978.     [CmdletBinding()]
  979.     Param(
  980.         [Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline=$True)]
  981.         [string[]]$Server,
  982.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  983.         [Alias("Password")]
  984.         [string]$ServerPassword,
  985.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  986.         [string]$LocationID,
  987.         [switch]$Backup = $False,
  988.         [switch]$Hide = $False,
  989.         [string]$Rename = $null
  990.     )
  991.            
  992.     Begin{
  993.         Clear-Variable PasswordArg, RenameArg, Svr, ServerList, Settings -EA 0 #Clearing Variables for use
  994.         # Gather install stats from registry or backed up settings
  995.         $Settings = Get-LTServiceInfo -ErrorAction SilentlyContinue
  996.         if (-not ($Settings)){
  997.             $Settings = Get-LTServiceInfoBackup -ErrorAction SilentlyContinue
  998.         }
  999.         $ServerList=@()
  1000.     }#End Begin
  1001.  
  1002.     Process{
  1003.         if (-not ($Server)){
  1004.             if ($Settings){
  1005.               $Server = $Settings|Select-object -Expand 'Server' -EA 0
  1006.             }
  1007.             if (-not ($Server)){
  1008.                 $Server = Read-Host -Prompt 'Provide the URL to your LabTech server (https://lt.domain.com):'
  1009.             }
  1010.         }
  1011.         if (-not ($LocationID)){
  1012.             if ($Settings){
  1013.                 $LocationID = $Settings|Select-object -Expand LocationID -EA 0
  1014.             }
  1015.             if (-not ($LocationID)){
  1016.                 $LocationID = Read-Host -Prompt 'Provide the LocationID'
  1017.             }
  1018.         }
  1019.         if (-not ($LocationID)){
  1020.             $LocationID = "1"
  1021.         }
  1022.         $ServerList += $Server
  1023.     }#End Process
  1024.  
  1025.     End{
  1026.         if ($Backup){
  1027.             New-LTServiceBackup
  1028.         }
  1029.  
  1030.         $RenameArg=''
  1031.         if ($Rename){
  1032.             $RenameArg = "-Rename $Rename"
  1033.         }
  1034.  
  1035.         if (($ServerPassword)){
  1036.             $PasswordArg = "-Password '$ServerPassword'"
  1037.         }
  1038.  
  1039.         Write-Host "Reinstalling LabTech with the following information, -Server $($ServerList -join ',') $PasswordArg -LocationID $LocationID $RenameArg"
  1040.         Write-Verbose "Starting: Uninstall-LTService -Server $($ServerList -join ',')"
  1041.         Try{
  1042.             Uninstall-LTService -Server $serverlist -ErrorAction Stop
  1043.         }#End Try
  1044.    
  1045.         Catch{
  1046.             Write-Error "ERROR: There was an error during the reinstall process while uninstalling. $($Error[0])" -ErrorAction Stop
  1047.         }#End Catch
  1048.  
  1049.         Start-Sleep 10
  1050.         Write-Verbose "Starting: Install-LTService -Server $($ServerList -join ',') $PasswordArg -LocationID $LocationID -Hide:`$$($Hide) $RenameArg"
  1051.         Try{
  1052.             Install-LTService -Server $ServerList $ServerPassword -LocationID $LocationID -Force -Hide:$Hide $RenameArg
  1053.         }#End Try
  1054.    
  1055.         Catch{
  1056.             Write-Error "ERROR: There was an error during the reinstall process while installing. $($Error[0])" -ErrorAction Stop
  1057.         }#End Catch
  1058.  
  1059.         If ($?){
  1060.             Return
  1061.         }
  1062.         else {
  1063.             $($Error[0])
  1064.         }
  1065.     }#End End
  1066. }#End Function Reinstall-LTService
  1067.  
  1068. Function Get-LTError{
  1069. <#
  1070. .SYNOPSIS
  1071.     This will pull the %ltsvcdir%\LTErrors.txt file into an object.
  1072.  
  1073. .EXAMPLE
  1074.     Get-LTError | where {(Get-date $_.Time) -gt (get-date).AddHours(-24)}
  1075.     Get a list of all errors in the last 24hr
  1076.  
  1077. .EXAMPLE
  1078.     Get-LTError | Out-Gridview
  1079.     Open the log file in a sortable searchable window.
  1080.  
  1081. .NOTES
  1082.     Version:        1.1
  1083.     Author:         Chris Taylor
  1084.     Website:        labtechconsulting.com
  1085.     Creation Date:  3/14/2016
  1086.     Purpose/Change: Initial script development
  1087.  
  1088.     Update Date: 6/1/2017
  1089.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1090.    
  1091. .LINK
  1092.     http://labtechconsulting.com
  1093. #>
  1094.  
  1095.     [CmdletBinding()]
  1096.     Param()
  1097.    
  1098.     Begin{
  1099.         $BasePath = $(Get-LTServiceInfo -ErrorAction SilentlyContinue|Select-object -Expand BasePath -EA 0)
  1100.         if (!$BasePath){$BasePath = "$env:windir\LTSVC"}
  1101.         if ($(Test-Path -Path $BasePath\LTErrors.txt) -eq $False) {
  1102.             Write-Error "ERROR: Unable to find log. $($Error[0])" -ErrorAction Stop
  1103.         }
  1104.     }#End Begin
  1105.  
  1106.     Process{
  1107.         Try{
  1108.             $errors = Get-Content "$BasePath\LTErrors.txt"
  1109.             $errors = $errors -join ' ' -split ':::'
  1110.             foreach($Line in $Errors){
  1111.                 $items = $Line -split "`t" -replace ' - ',''
  1112.                 if ($items[1]){
  1113.                     $object = New-Object -TypeName PSObject
  1114.                     $object | Add-Member -MemberType NoteProperty -Name ServiceVersion -Value $items[0]
  1115.                     $object | Add-Member -MemberType NoteProperty -Name Timestamp -Value $([datetime]$items[1])
  1116.                     $object | Add-Member -MemberType NoteProperty -Name Message -Value $items[2]
  1117.                     Write-Output $object
  1118.                 }
  1119.             }
  1120.            
  1121.         }#End Try
  1122.    
  1123.         Catch{
  1124.             Write-Error "ERROR: There was an error reading the log. $($Error[0])" -ErrorAction Stop
  1125.         }#End Catch
  1126.     }#End Process
  1127.  
  1128.     End{
  1129.         if ($?){
  1130.         }
  1131.         Else {$Error[0]}
  1132.        
  1133.     }#End End
  1134. }#End Function Get-LTError
  1135.  
  1136.  
  1137. Function Reset-LTService{
  1138. <#
  1139. .SYNOPSIS
  1140.     This function will remove local settings on the agent.
  1141.  
  1142. .DESCRIPTION
  1143.     This function can remove some of the agents local settings.
  1144.     ID, MAC, LocationID
  1145.     The function will stop the services, make the change, then start the services.
  1146.     Resetting all of these will force the agent to check in as a new agent.
  1147.     If you have MAC filtering enabled it should check back in with the same ID.
  1148.     This function is useful for duplicate agents.
  1149.  
  1150. .PARAMETER ID
  1151.     This will reset the AgentID of the computer
  1152.  
  1153. .PARAMETER Location
  1154.     This will reset the LocationID of the computer
  1155.  
  1156. .PARAMETER MAC
  1157.     This will reset the MAC of the computer
  1158.  
  1159. .EXAMPLE
  1160.     Reset-LTService
  1161.     This resets the ID, MAC and LocationID on the agent.
  1162.  
  1163. .EXAMPLE
  1164.     Reset-LTService -ID
  1165.     This resets only the ID of the agent.
  1166.  
  1167. .NOTES
  1168.     Version:        1.1
  1169.     Author:         Chris Taylor
  1170.     Website:        labtechconsulting.com
  1171.     Creation Date:  3/14/2016
  1172.     Purpose/Change: Initial script development
  1173.  
  1174.     Update Date: 6/1/2017
  1175.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1176.    
  1177. .LINK
  1178.     http://labtechconsulting.com
  1179. #>
  1180.  
  1181.     [CmdletBinding()]
  1182.     Param(
  1183.         [switch]$ID,
  1184.         [switch]$Location,
  1185.         [switch]$MAC        
  1186.     )  
  1187.    
  1188.     Begin{
  1189.         if (!(Get-Service 'LTService','LTSvcMon' -ErrorAction SilentlyContinue)) {
  1190.             Write-Error "ERROR: LabTech Services NOT Found $($Error[0])" -ErrorAction Stop
  1191.         }
  1192.         $Reg = 'HKLM:\Software\LabTech\Service'
  1193.         if (!($ID -or $LocationID -or $MAC)){
  1194.             $ID=$true
  1195.             $Location=$true
  1196.             $MAC=$true
  1197.         }
  1198.         Write-Output "OLD ID: $(Get-LTServiceInfo|Select-object -Expand ID -EA 0) LocationID: $(Get-LTServiceInfo|Select-object -Expand LocationID -EA 0) MAC: $(Get-LTServiceInfo|Select-object -Expand MAC -EA 0)"
  1199.        
  1200.     }#End Begin
  1201.  
  1202.     Process{
  1203.         Try{
  1204.             Stop-LTService
  1205.             if ($ID) {
  1206.                 Write-Output ".Removing ID"
  1207.                 Remove-ItemProperty -Name ID -Path $Reg -ErrorAction SilentlyContinue            
  1208.             }
  1209.             if ($Location) {
  1210.                 Write-Output ".Removing LocationID"
  1211.                 Remove-ItemProperty -Name LocationID -Path $Reg -ErrorAction SilentlyContinue
  1212.             }
  1213.             if ($MAC) {
  1214.                 Write-Output ".Removing MAC"
  1215.                 Remove-ItemProperty -Name MAC -Path $Reg -ErrorAction SilentlyContinue
  1216.             }
  1217.             Start-LTService
  1218.             $timeout = new-timespan -Minutes 1
  1219.             $sw = [diagnostics.stopwatch]::StartNew()
  1220.             While (!(Get-LTServiceInfo|Select-object -Expand ID -EA 0) -or !(Get-LTServiceInfo|Select-object -Expand LocationID -EA 0) -or !(Get-LTServiceInfo|Select-object -Expand MAC -EA 0) -and $($sw.elapsed) -lt $timeout){
  1221.                 Write-Host -NoNewline '.'
  1222.                 Start-Sleep 2
  1223.             }
  1224.  
  1225.         }#End Try
  1226.    
  1227.         Catch{
  1228.             Write-Error "ERROR: There was an error durring the reset process. $($Error[0])" -ErrorAction Stop
  1229.         }#End Catch
  1230.     }#End Process
  1231.  
  1232.     End{
  1233.         if ($?){
  1234.             Write-Output ""
  1235.             Write-Output "NEW ID: $(Get-LTServiceInfo|Select-object -Expand ID -EA 0) LocationID: $(Get-LTServiceInfo|Select-object -Expand LocationID -EA 0) MAC: $(Get-LTServiceInfo|Select-object -Expand MAC -EA 0)"
  1236.         }
  1237.         Else {$Error[0]}
  1238.     }#End End
  1239. }#End Function Reset-LTService
  1240.  
  1241. Function Hide-LTAddRemove{
  1242. <#
  1243. .SYNOPSIS
  1244.     This function hides the LabTech install from the Add/Remove Programs list.
  1245.  
  1246. .DESCRIPTION
  1247.     This function will rename the DisplayName registry key to hide it from the Add/Remove Programs list.
  1248.  
  1249. .NOTES
  1250.     Version:        1.1
  1251.     Author:         Chris Taylor
  1252.     Website:        labtechconsulting.com
  1253.     Creation Date:  3/14/2016
  1254.     Purpose/Change: Initial script development
  1255.  
  1256.     Update Date: 6/1/2017
  1257.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1258.    
  1259. .LINK
  1260.     http://labtechconsulting.com
  1261. #>
  1262.     [CmdletBinding()]
  1263.     Param()
  1264.  
  1265.     Begin{
  1266.         $RegRoots = 'HKLM:\SOFTWARE\Classes\Installer\Products\C4D064F3712D4B64086B5BDE05DBC75F','HKLM:\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC'
  1267.         foreach($RegRoot in $RegRoots){
  1268.             if (Get-ItemProperty $RegRoot -Name ProductName -ErrorAction SilentlyContinue) {
  1269.                 Write-Output "LabTech found in add/remove programs."
  1270.             }
  1271.             else {
  1272.                 if (Get-ItemProperty $RegRoot -Name HiddenProductName -ErrorAction SilentlyContinue) {
  1273.                     Write-Error "LabTech already hidden from add/remove programs." -ErrorAction Stop
  1274.                 }    
  1275.             }
  1276.         }
  1277.        
  1278.     }#End Begin
  1279.  
  1280.     Process{
  1281.         Try{
  1282.             Rename-ItemProperty $RegRoot -Name ProductName -NewName HiddenProductName
  1283.         }#End Try
  1284.    
  1285.         Catch{
  1286.             Write-Error "There was an error renaming the registry key. $($Error[0])" -ErrorAction Stop
  1287.         }#End Catch
  1288.     }#End Process
  1289.  
  1290.     End{
  1291.         if ($?){
  1292.             Write-Output "LabTech is now hidden from Add/Remove Programs."
  1293.         }
  1294.         else {$Error[0]}
  1295.     }#End End
  1296. }#End Function Hide-LTAddRemove
  1297.  
  1298. Function Show-LTAddRemove{
  1299. <#
  1300. .SYNOPSIS
  1301.     This function shows the LabTech install in the add/remove programs list.
  1302.  
  1303. .DESCRIPTION
  1304.     This function will rename the HiddenDisplayName registry key to show it in the add/remove programs list.
  1305.     If there is not HiddenDisplayName key the function will import a new entry.
  1306.  
  1307. .NOTES
  1308.     Version:        1.1
  1309.     Author:         Chris Taylor
  1310.     Website:        labtechconsulting.com
  1311.     Creation Date:  3/14/2016
  1312.     Purpose/Change: Initial script development
  1313.  
  1314.     Update Date: 6/1/2017
  1315.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1316.    
  1317. .LINK
  1318.     http://labtechconsulting.com
  1319. #>
  1320.     [CmdletBinding()]
  1321.     Param()
  1322.  
  1323.     Begin{
  1324.         $RegRoots = 'HKLM:\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC'
  1325.     }#End Begin
  1326.  
  1327.     Process{
  1328.         Try{
  1329.             foreach($RegRoot in $RegRoots){
  1330.  
  1331.                 if (Get-ItemProperty $RegRoot -Name HiddenProductName -ErrorAction SilentlyContinue){
  1332.                     Rename-ItemProperty $RegRoot -Name HiddenProductName -NewName ProductName
  1333.                 }
  1334.                 else{
  1335.                     $RegImport = @'
  1336. [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC]
  1337. "PackageCode"="8059C8AD908AB434A9F2225AF86355C2"
  1338. "Language"=dword:00000409
  1339. "Version"=dword:0b00016d
  1340. "Assignment"=dword:00000001
  1341. "AdvertiseFlags"=dword:00000184
  1342. "ProductIcon"="C:\\WINDOWS\\Installer\\{58A3001D-B675-4D67-A5A1-0FA9F08CF7CA}\\LabTeCh.ico"
  1343. "InstanceType"=dword:00000000
  1344. "AuthorizedLUAApp"=dword:00000000
  1345. "DeploymentFlags"=dword:00000003
  1346. "Clients"=hex(7):3a,00,00,00,00,00
  1347. "ProductName"="LabTechοΏ½ Software Remote Agent"
  1348. '@
  1349.                     $RegImport | Out-File "$env:TEMP\LT.reg" -Force
  1350.                     Start-Process -Wait -FilePath reg -ArgumentList "import $($env:TEMP)\LT.reg"
  1351.                     Remove-Item "$env:TEMP\LT.reg" -Force
  1352.                     New-ItemProperty -Path "$RegRoot\SourceList" -Name LastUsedSource -Value "u;1;$((Get-LTServiceInfo|Select-object -Expand 'Server Address' -EA 0).Split(';'))/Labtech/" -PropertyType ExpandString -Force | Out-Null
  1353.                     New-ItemProperty -Path "$RegRoot\SourceList\URL" -Name 1 -Value "$((Get-LTServiceInfo|Select-object -Expand 'Server Address' -EA 0).Split(';'))/Labtech/" -PropertyType ExpandString -Force | Out-Null
  1354.                 }
  1355.             }
  1356.         }#End Try
  1357.    
  1358.         Catch{
  1359.             Write-Error "There was an error renaming the registry key. $($Error[0])" -ErrorAction Stop
  1360.         }#End Catch
  1361.     }#End Process
  1362.  
  1363.     End{
  1364.         if ($?) {
  1365.             Write-Output "LabTech is now shown in Add/Remove Programs."
  1366.         }
  1367.         Else{$Error[0]}
  1368.     }#End End
  1369. }#End Function Show-LTAddRemove
  1370.  
  1371. Function Test-LTPorts{
  1372. <#
  1373. .SYNOPSIS
  1374.     This function will attempt to connect to all required TCP ports.
  1375.  
  1376. .DESCRIPTION
  1377.     The function will make sure that LTTray is using UDP 42000.
  1378.     It will then test all the required TCP ports.
  1379.  
  1380. .PARAMETER Server
  1381.     This is the URL to your LabTech server.
  1382.     Example: https://lt.domain.com
  1383.     This is used to download the installation and removal utilities.
  1384.     If no server is provided the uninstaller will use Get-LTServiceInfo to get the server address.
  1385.     If it is unable to find LT currently installed it will try Get-LTServiceInfoBackup
  1386.  
  1387. .PARAMETER Quiet
  1388.     This will return a bool for connectivity to the Server
  1389.  
  1390. .NOTES
  1391.     Version:        1.5
  1392.     Author:         Chris Taylor
  1393.     Website:        labtechconsulting.com
  1394.     Creation Date:  3/14/2016
  1395.     Purpose/Change: Initial script development
  1396.  
  1397.     Update Date:    5/11/2017
  1398.     Purpose/Change: Quiet feature
  1399.  
  1400.     Update Date: 6/1/2017
  1401.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1402.  
  1403.     Update Date: 6/10/2017
  1404.     Purpose/Change: Updates for pipeline input, support for multiple servers
  1405.  
  1406.     Update Date: 8/24/2017
  1407.     Purpose/Change: Update to use Clear-Variable.
  1408.    
  1409.     Update Date: 8/29/2017
  1410.     Purpose/Change: Added Server Address Format Check
  1411.    
  1412. .LINK
  1413.     http://labtechconsulting.com
  1414. #>
  1415.     [CmdletBinding()]
  1416.     Param(
  1417.         [Parameter(ValueFromPipelineByPropertyName = $true, ValueFromPipeline=$True)]
  1418.         [string[]]$Server,
  1419.         [Parameter(ValueFromPipelineByPropertyName = $true)]
  1420.         [switch]$Quiet
  1421.     )
  1422.  
  1423.     Begin{
  1424.         Function Private:TestPort{
  1425.         Param(
  1426.             [parameter(ParameterSetName='ComputerName', Position=0)]
  1427.             [string]
  1428.             $ComputerName,
  1429.  
  1430.             [parameter(ParameterSetName='IP', Position=0)]
  1431.             [System.Net.IPAddress]
  1432.             $IPAddress,
  1433.  
  1434.             [parameter(Mandatory=$true , Position=1)]
  1435.             [int]
  1436.             $Port
  1437.             )
  1438.  
  1439.         $RemoteServer = If ([string]::IsNullOrEmpty($ComputerName)) {$IPAddress} Else {$ComputerName};
  1440.    
  1441.         $test = New-Object System.Net.Sockets.TcpClient;
  1442.         Try
  1443.         {
  1444.             Write-Output "Connecting to $($RemoteServer):$Port (TCP)..";
  1445.             $test.Connect($RemoteServer, $Port);
  1446.             Write-Output "Connection successful";
  1447.         }
  1448.         Catch
  1449.         {
  1450.             Write-Output "ERROR: Connection failed";
  1451.             $Global:PortTestError = 1
  1452.         }
  1453.         Finally
  1454.         {
  1455.             $test.Close();
  1456.         }
  1457.  
  1458.     }#End Function TestPort
  1459.  
  1460.         Clear-Variable CleanSvr,svr,proc,processes,port,netstat,line -EA 0 #Clearing Variables for use
  1461.  
  1462.         if (-not ($Quiet)){
  1463.             #Learn LTTrayPort if available.
  1464.             $Port = (Get-LTServiceInfo -EA 0|Select-Object -Expand TrayPort -EA 0)
  1465.             if (-not ($Port) -or $Port -notmatch '^\d+$') {$Port=42000}
  1466.             [array]$processes = @()
  1467.             #Get all processes that are using LTTrayPort (Default 42000)
  1468.             $netstat = netstat.exe -a -o -n | Select-String $Port -EA 0
  1469.             foreach ($line in $netstat) {
  1470.                 $process += ($line -split '  {3,}')[-1]
  1471.             }
  1472.             $processes = $processes | Where-Object {$_ -gt 0 -and $_ -match '^\d+$'}| Sort-Object | Get-Unique
  1473.             if ($processes) {
  1474.                 foreach ($proc in $processes) {
  1475.                     if ((Get-Process -ID $proc -EA 0|Select-object -Expand ProcessName -EA 0) -eq 'LTSvc') {
  1476.                         Write-Output "LTSvc is using port $Port"
  1477.                     } else {
  1478.                         Write-Output "Error: $(Get-Process -ID $proc|Select-object -Expand ProcessName -EA 0) is using port $Port"
  1479.                     }
  1480.                 }
  1481.             }
  1482.         }    
  1483.     }#End Begin
  1484.  
  1485.     Process{
  1486.         if (-not ($Server)){
  1487.             Write-Verbose 'No Server Input - Checking for names.'
  1488.             $Server = Get-LTServiceInfo -EA 0|Select-Object -Expand 'Server'
  1489.         }
  1490.         foreach ($svr in $Server) {
  1491.                 if ($Quiet){
  1492.                     Test-Connection $Svr -Quiet
  1493.                     return
  1494.                 }
  1495.  
  1496.                 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_-]*){1,})$') {
  1497.                     Try{
  1498.                         $CleanSvr = ($Svr -replace("(http|https)://",'')|Foreach {$_.Trim()})
  1499.                         Write-Output "Testing connectivity to required TCP ports"
  1500.                         TestPort -ComputerName $CleanSvr -Port 70
  1501.                         TestPort -ComputerName $CleanSvr -Port 80
  1502.                         TestPort -ComputerName $CleanSvr -Port 443
  1503.                         TestPort -ComputerName mediator.labtechsoftware.com -Port 8002
  1504.  
  1505.                     }#End Try
  1506.  
  1507.                     Catch{
  1508.                       Write-Error "ERROR: There was an error testing the ports. $($Error[0])" -ErrorAction Stop
  1509.                     }#End Catch
  1510.                 } else {
  1511.                     Write-Warning "Server address $($Svr) is not a valid address or is not formatted correctly. Example: https://lt.domain.com"
  1512.                 }#End If
  1513.                
  1514.             }#End Foreach
  1515.       }#End Process
  1516.  
  1517.       End{
  1518.         If ($?){
  1519.             if (-not ($Quiet)){
  1520.                 Write-Output "Finished"
  1521.             }          
  1522.         }
  1523.         else{$Error[0]}
  1524.       }#End End
  1525.  
  1526. }#End Function Test-LTPorts
  1527.  
  1528. Function Get-LTLogging{
  1529. <#
  1530. .SYNOPSIS
  1531.     This function will pull the logging level of the LabTech service.
  1532.  
  1533. .NOTES
  1534.     Version:        1.1
  1535.     Author:         Chris Taylor
  1536.     Website:        labtechconsulting.com
  1537.     Creation Date:  3/14/2016
  1538.     Purpose/Change: Initial script development
  1539.  
  1540.     Update Date: 6/1/2017
  1541.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1542.    
  1543. .LINK
  1544.     http://labtechconsulting.com
  1545. #>
  1546.     [CmdletBinding()]
  1547.     Param ()
  1548.      
  1549.   Begin{
  1550.     Write-Verbose "Verbose: Checking for registry keys."
  1551.     if ((Test-Path 'HKLM:\SOFTWARE\LabTech\Service\settings') -eq $False){
  1552.         Write-Error "ERROR: Unable to find logging settings for LTSvc. Make sure the agent is installed." -ErrorAction Stop
  1553.     }
  1554.   }#End Begin
  1555.  
  1556.   Process{
  1557.     Try{
  1558.         $Value = (Get-LTServiceSettings|Select-object -Expand Debuging -EA 0)
  1559.     }#End Try
  1560.    
  1561.     Catch{
  1562.       Write-Error "ERROR: There was a problem reading the registry key. $($Error[0])" -ErrorAction Stop
  1563.     }#End Catch
  1564.   }#End Process
  1565.  
  1566.   End{
  1567.     if ($?){
  1568.         if ($value -eq 1){
  1569.             Write-Output "Current logging level: Normal"
  1570.         }
  1571.         elseif ($value -eq 1000){
  1572.             Write-Output "Current logging level: Verbose"
  1573.         }
  1574.         else{
  1575.             Write-Error "ERROR: Unknown Logging level $(Get-LTServiceInfo|Select-object -Expand Debuging -EA 0)" -ErrorAction Stop
  1576.         }
  1577.     }    
  1578.   }#End End
  1579. }#End Function Get-LTLogging
  1580.  
  1581. Function Set-LTLogging{
  1582. <#
  1583. .SYNOPSIS
  1584.         This function will set the logging level of the LabTech service.
  1585.  
  1586. .NOTES
  1587.     Version:        1.1
  1588.     Author:         Chris Taylor
  1589.     Website:        labtechconsulting.com
  1590.     Creation Date:  3/14/2016
  1591.     Purpose/Change: Initial script development
  1592.  
  1593.     Update Date: 6/1/2017
  1594.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1595.    
  1596. .LINK
  1597.     http://labtechconsulting.com
  1598. #>
  1599.    Param (
  1600.         [switch]$Normal,
  1601.         [switch]$Verbose
  1602.     )
  1603.  
  1604.      
  1605.   Begin{
  1606.     if ($Normal -ne $true -and $Verbose -ne $true ){
  1607.         Write-Error "Please provide a logging level. -Normal or -Verbose" -ErrorAction Stop
  1608.     }
  1609.  
  1610.   }#End Begin
  1611.  
  1612.   Process{
  1613.     Try{
  1614.         Stop-LTService
  1615.         if ($Normal){
  1616.             Set-ItemProperty HKLM:\SOFTWARE\LabTech\Service\Settings -Name 'Debuging' -Value 1
  1617.         }
  1618.         if ($Verbose){
  1619.             Set-ItemProperty HKLM:\SOFTWARE\LabTech\Service\Settings -Name 'Debuging' -Value 1000
  1620.         }
  1621.         Start-LTService
  1622.     }#End Try
  1623.    
  1624.     Catch{
  1625.       Write-Error "ERROR: There was a problem writing the registry key. $($Error[0])" -ErrorAction Stop
  1626.     }#End Catch
  1627.   }#End Process
  1628.  
  1629.   End{
  1630.     if ($?){
  1631.         Get-LTLogging          
  1632.     }    
  1633.   }#End End
  1634. }#End Function Set-LTLogging
  1635.  
  1636. Function Get-LTProbeErrors {
  1637. <#
  1638. .SYNOPSIS
  1639.     This will pull the %ltsvcdir%\LTProbeErrors.txt file into an object.
  1640.  
  1641. .EXAMPLE
  1642.     Get-LTProbeErrors | where {(Get-date $_.Time) -gt (get-date).AddHours(-24)}
  1643.     Get a list of all errors in the last 24hr
  1644.  
  1645. .EXAMPLE
  1646.     Get-LTProbeErrors | Out-Gridview
  1647.     Open the log file in a sortable searchable window.
  1648.  
  1649. .NOTES
  1650.     Version:        1.1
  1651.     Author:         Chris Taylor
  1652.     Website:        labtechconsulting.com
  1653.     Creation Date:  3/14/2016
  1654.     Purpose/Change: Initial script development
  1655.  
  1656.     Update Date: 6/1/2017
  1657.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1658.    
  1659. .LINK
  1660.     http://labtechconsulting.com
  1661. #>
  1662.  
  1663.     [CmdletBinding()]
  1664.     Param()
  1665.    
  1666.     Begin{
  1667.         $BasePath = $(Get-LTServiceInfo -ErrorAction SilentlyContinue|Select-object -Expand BasePath -EA 0)
  1668.         if (!$BasePath){$BasePath = "$env:windir\LTSVC"}
  1669.         if ($(Test-Path -Path $BasePath\LTProbeErrors.txt) -eq $False) {
  1670.             Write-Error "ERROR: Unable to find log. $($Error[0])" -ErrorAction Stop
  1671.         }
  1672.     }#End Begin
  1673.     process{
  1674.         $errors = Get-Content $BasePath\LTProbeErrors.txt
  1675.         $errors = $errors -join ' ' -split ':::'
  1676.         foreach($Line in $Errors){
  1677.             $items = $Line -split "`t" -replace ' - ',''
  1678.             $object = New-Object -TypeName PSObject
  1679.             $object | Add-Member -MemberType NoteProperty -Name ServiceVersion -Value $items[0]
  1680.             $object | Add-Member -MemberType NoteProperty -Name Timestamp -Value $([datetime]$items[1])
  1681.             $object | Add-Member -MemberType NoteProperty -Name Message -Value $items[2]
  1682.             Write-Output $object
  1683.         }
  1684.     }
  1685.     End{
  1686.         if ($?){
  1687.         }
  1688.         Else {$Error[0]}
  1689.        
  1690.     }#End End
  1691. }#End Function Get-LTProbeErrors
  1692.  
  1693. Function New-LTServiceBackup {
  1694. <#
  1695. .SYNOPSIS
  1696.     This function will backup all the reg keys to 'HKLM\SOFTWARE\LabTechBackup'
  1697.     This will also backup those files to "$((Get-LTServiceInfo).BasePath)Backup"
  1698.  
  1699. .NOTES
  1700.     Version:        1.3
  1701.     Author:         Chris Taylor
  1702.     Website:        labtechconsulting.com
  1703.     Creation Date:  5/11/2017
  1704.     Purpose/Change: Initial script development
  1705.  
  1706.     Update Date: 6/1/2017
  1707.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1708.    
  1709.     Update Date: 6/7/2017
  1710.     Purpose/Change: Updated error handling.
  1711.    
  1712.     Update Date: 8/24/2017
  1713.     Purpose/Change: Update to use Clear-Variable.
  1714.    
  1715. .LINK
  1716.     http://labtechconsulting.com
  1717. #>
  1718.     [CmdletBinding()]
  1719.     Param ()
  1720.      
  1721.   Begin{
  1722.     Clear-Variable LTPath,BackupPath,Keys,Path,Result,Reg,RegPath -EA 0 #Clearing Variables for use
  1723.     $LTPath = "$(Get-LTServiceInfo -EA 0|Select-Object -Expand BasePath -EA 0)"
  1724.     if (-not ($LTPath)) {
  1725.       Write-Error "ERROR: Unable to find LTSvc folder path." -ErrorAction Stop
  1726.     }
  1727.     $BackupPath = "$($LTPath)Backup"
  1728.     $Keys = "HKLM\SOFTWARE\LabTech"
  1729.     $RegPath = "$BackupPath\LTBackup.reg"
  1730.    
  1731.     Write-Verbose "Verbose: Checking for registry keys."
  1732.     if ((Test-Path ($Keys -replace '^(H[^\\]*)','$1:')) -eq $False){
  1733.         Write-Error "ERROR: Unable to find registry information on LTSvc. Make sure the agent is installed." -ErrorAction Stop
  1734.         Return
  1735.     }
  1736.     if ($(Test-Path -Path $LTPath -PathType Container) -eq $False) {
  1737.       Write-Error "ERROR: Unable to find LTSvc folder path $LTPath" -ErrorAction Stop
  1738.     }
  1739.     New-Item $BackupPath -type directory -ErrorAction SilentlyContinue | Out-Null
  1740.     if ($(Test-Path -Path $BackupPath -PathType Container) -eq $False) {
  1741.       Write-Error "ERROR: Unable to create backup folder path $BackupPath" -ErrorAction Stop
  1742.     }
  1743.   }#End Begin
  1744.  
  1745.   Process{
  1746.     Try{
  1747.     Copy-Item $LTPath $BackupPath -Recurse -Force
  1748.     }#End Try
  1749.    
  1750.     Catch{
  1751.     Write-Error "ERROR: There was a problem backing up the LTSvc Folder. $($Error[0])"
  1752.     }#End Catch
  1753.  
  1754.     Try{
  1755.     $Result = reg.exe export "$Keys" "$RegPath" /y 2>''
  1756.     $Reg = Get-Content $RegPath
  1757.     $Reg = $Reg -replace [Regex]::Escape('[HKEY_LOCAL_MACHINE\SOFTWARE\LabTech'),'[HKEY_LOCAL_MACHINE\SOFTWARE\LabTechBackup'
  1758.     $Reg | Out-File $RegPath
  1759.     $Result = reg.exe import "$RegPath" 2>''
  1760.     $True | Out-Null #Protection to prevent exit status error
  1761.     }#End Try
  1762.  
  1763.     Catch{
  1764.     Write-Error "ERROR: There was a problem backing up the LTSvc Registry keys. $($Error[0])"
  1765.     }#End Catch
  1766.   }#End Process
  1767.  
  1768.   End{
  1769.     If ($?){
  1770.     Write-Output "The LabTech Backup has been created."
  1771.     }
  1772.     Else {
  1773.         Write-Error "ERROR: There was a problem completing the LTSvc Backup. $($Error[0])"
  1774.     }#End If
  1775.   }#End End
  1776. }#End Function New-LTServiceBackup
  1777.  
  1778. Function Get-LTServiceInfoBackup {
  1779. <#
  1780. .SYNOPSIS
  1781.     This function will pull all of the backed up registry data into an object.
  1782.  
  1783. .NOTES
  1784.     Version:        1.1
  1785.     Author:         Chris Taylor
  1786.     Website:        labtechconsulting.com
  1787.     Creation Date:  5/11/2017
  1788.     Purpose/Change: Initial script development
  1789.  
  1790.     Update Date: 6/1/2017
  1791.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1792.    
  1793. .LINK
  1794.     http://labtechconsulting.com
  1795. #>
  1796.     [CmdletBinding()]
  1797.     Param ()
  1798.      
  1799.   Begin{
  1800.     Write-Verbose "Verbose: Checking for registry keys."
  1801.     If ((Test-Path 'HKLM:\SOFTWARE\LabTechBackup\Service') -eq $False){
  1802.         Write-Error "ERROR: Unable to find backup information on LTSvc. Use New-LTServiceBackup to create a settings backup."
  1803.         Return
  1804.     }
  1805.     $exclude = "PSParentPath","PSChildName","PSDrive","PSProvider","PSPath"
  1806.   }#End Begin
  1807.  
  1808.   Process{
  1809.     Try{
  1810.         $key = Get-ItemProperty HKLM:\SOFTWARE\LabTechBackup\Service -ErrorAction Stop | Select * -exclude $exclude
  1811.         if (($key|Get-Member|Where {$_.Name -match 'BasePath'})) {
  1812.             $key.BasePath = [System.Environment]::ExpandEnvironmentVariables($key.BasePath)
  1813.         }
  1814.         if (($key|Get-Member|Where {$_.Name -match 'Server Address'})) {
  1815.         $Servers = ($Key|Select-Object -Expand 'Server Address' -EA 0).Split('|')|Foreach {$_.Trim()}
  1816.         Add-Member -InputObject $key -MemberType NoteProperty -Name 'Server' -Value $Servers -Force
  1817.     }
  1818.     }#End Try
  1819.    
  1820.     Catch{
  1821.       Write-Error "ERROR: There was a problem reading the registry keys. $($Error[0])"
  1822.     }#End Catch
  1823.   }#End Process
  1824.  
  1825.   End{
  1826.     If ($?){
  1827.         $key
  1828.     }    
  1829.   }#End End
  1830. }#End Function Get-LTServiceInfoBackup
  1831.  
  1832. Function Rename-LTAddRemove{
  1833. <#
  1834. .SYNOPSIS
  1835.     This function renames the LabTech install as shown in the Add/Remove Programs list.
  1836.  
  1837. .DESCRIPTION
  1838.     This function will change the value of the DisplayName registry key to effect Add/Remove Programs list.
  1839.  
  1840. .NOTES
  1841.     Version:        1.1
  1842.     Author:         Chris Taylor
  1843.     Website:        labtechconsulting.com
  1844.     Creation Date:  5/14/2017
  1845.     Purpose/Change: Initial script development
  1846.  
  1847.     Update Date: 6/1/2017
  1848.     Purpose/Change: Updates for better overall compatibility, including better support for PowerShell V2
  1849.    
  1850. .LINK
  1851.     http://labtechconsulting.com
  1852. #>
  1853.     [CmdletBinding()]
  1854.     Param(
  1855.         [Parameter(Mandatory=$True)]
  1856.         $Name
  1857.     )
  1858.  
  1859.     Begin{
  1860.         $RegRoot = 'HKLM:\SOFTWARE\Classes\Installer\Products\D1003A85576B76D45A1AF09A0FC87FAC'      
  1861.     }#End Begin
  1862.  
  1863.     Process{
  1864.         Try{
  1865.             Set-ItemProperty $RegRoot -Name ProductName -Value $Name
  1866.         }#End Try
  1867.    
  1868.         Catch{
  1869.             Write-Error "There was an error renaming the registry key. $($Error[0])" -ErrorAction Stop
  1870.         }#End Catch
  1871.     }#End Process
  1872.  
  1873.     End{
  1874.         if ($?){
  1875.             Write-Output "LabTech is now listed as '$Name' in Add/Remove Programs."
  1876.         }
  1877.         else {$Error[0]}
  1878.     }#End End
  1879. }#End Function Rename-LTAddRemove
  1880.  
  1881. #endregion Functions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement