Public/InstallHelpers/Install.Service.Functions.psm1

#Requires -Version 5.0
#Requires -RunAsAdministrator
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop";


# DOCS: http://docs.topshelf-project.com/en/latest/overview/commandline.html
# NOTE: Was unable to reliably remove the service using the methods below
# [string] $command = "sc delete $svcName"
# $command | cmd.exe
# (Get-WmiObject Win32_Service -filter "name='$svcName'").Delete()
function _uninstallService(
    [Parameter(Position=0,mandatory=$true)]
    [string] $svcName,

    [Parameter(Position=1,mandatory=$true)]
    [string] $pathToExe
) {
    Set-Service -Name $svcName -Status Stopped -ErrorAction SilentlyContinue
    if ( (Test-Path -Path $pathToExe) -eq $false) {
        throw "ERROR: Service installer EXE not found in $pathToExe. Please manually uninstall the $svcName service (if installed) and re-run this installer."
    }
    & $pathToExe uninstall `
        -servicename:$svcName
}


# DOCS: http://docs.topshelf-project.com/en/latest/overview/commandline.html
# NOTE: Avoiding starting service so we can test this function without worrying about port conflicts
function InstallService(
    [Parameter(Position=0,mandatory=$true)]
    [string] $svcName,

    [Parameter(Position=1,mandatory=$true)]
    [string] $pathToExe,

    [Parameter(Position=2,mandatory=$false)]
    [string] $description = 'DSI Training Notifier Server'
) {
    _uninstallService -svcName $svcName -pathToExe $pathToExe    
    # NOTE: This guard seems to produce false positives due to residue left from the service
    # if ($null -eq (Get-Service -Name $svcName -ErrorAction SilentlyContinue)) {
    # throw "ERROR: Service $svcName is currently installed. Please manually uninstall it and re-run this installer"
    # }
    & $pathToExe install `
        -servicename:$svcName `
        -displayname:$svcName `
        -description $description `
        --autostart `
        --localsystem `
        --delayed
}


# NOTE: Skip automated testing
function StopService(
    [Parameter(Position=0,mandatory=$true)]
    [string] $svcName    
) {    
    Set-Service -Name $svcName -Status Stopped -Verbose -ErrorAction SilentlyContinue
}


# NOTE: Skip automated testing
function StartService(
    [Parameter(Position=0,mandatory=$true)]
    [string] $svcName    
) {    
    Set-Service -Name $svcName -Status Running -Verbose
}


Export-ModuleMember -Function "*"