Install-ALOpsExternalDeployer.ps1

function Install-ALOpsExternalDeployer(){
    [CmdletBinding()]
    param
    (
        [switch] $Remove
    )

    #*** Settings ***
    $DisplayName = "ALOps External Deployer"
    $ServiceName = "ALOpsExternalDeployer"

    Write-Host "*** Deploy [$($DisplayName)]" -ForegroundColor Green
    $ErrorActionPreference = "Stop"        

    #*** Check Prerequisites ***
    Write-Host "*** Check dotnet IntallUtil" -ForegroundColor Green
    $InstallUtilPath = Get-DotnetInstallUtil

    #*** Stop Existing Service ***
    $alopsService = get-service -Name $ServiceName -ErrorAction SilentlyContinue
    $tryCount = 0
    if ($null -ne $alopsService){
        Write-Host "*** Stopping existing service" -ForegroundColor Green
        Stop-Service -Name $ServiceName
        while ($alopsService.Status.ToString().ToUpper() -ne "Stopped".ToUpper() ){
            $tryCount += 1;            
            Start-Sleep -Seconds 1
            $alopsService = get-service -Name $ServiceName

            if ($tryCount -gt 15){
                $ServicePID = (get-wmiobject win32_service | Where-Object { $_.name -eq $ServiceName }).processID
                Stop-Process $ServicePID -Force
            }
        }
        Start-Sleep -Seconds 1

        Write-Host "*** Uninstall existing service" -ForegroundColor Green
        $oldService = get-wmiobject win32_service | Where-Object { $_.name -eq $ServiceName} | Select-Object -Property  Name, DisplayName, State, PathName
        Write-Host "$($oldService | format-list -Property * | out-string)"
        & "$($InstallUtilPath)" /u "$($oldService.PathName)"
    }

    if (-not $Remove) {
        #*** Install Service ***
        Write-Host "*** Install Agent" -ForegroundColor Green
        $alopsService = get-service -Name $ServiceName -ErrorAction SilentlyContinue
        if ($null -eq $alopsService) {
            $ServicePath = Join-Path -Path ((get-Module ALOps.ExternalDeployer).ModuleBase) -ChildPath "bin\ALOpsExternalDeployer.exe"
        
            & "$($InstallUtilPath)" "$($ServicePath)"
        }

        #*** Start Service ***
        Write-Host "*** Start Service [$($ServiceName)]" -ForegroundColor Green
        Start-Service -Name $ServiceName
    }
    
    Write-Host "Use [New-ALOpsExternalDeployer -ServerInstance BC] to link a BC Server Instance with the [ALOps External Deployer] service." -ForegroundColor Green
}