Core/Services-Module.psm1

$ErrorActionPreference = "Stop"

choco upgrade nssm -y --limitoutput | Out-Null
RefreshEnvironment

function NewWindowsService {
    [CmdletBinding()]
    Param
    (
        [string]$Service,
        [string]$Directory,
        [int]$Port,
        [string]$DisplayName,
        [string]$Description
    )

    DeleteWindowsService -Service $Service

    Write-Output "Creating $Service service..."

    nssm install "$Service" "$Directory\bin\solr.cmd" "-f" "-p $Port"
    nssm set "$Service" DisplayName "$DisplayName" 
    nssm set "$Service" Description "$Description"

    Write-Output "Done."
}

function StartWindowsService {
    [CmdletBinding()]
    Param
    (
        [string]$Service
    )

    $svc = Get-Service "$Service" -ErrorAction SilentlyContinue

    if ($svc.Status -ne "Running") {
        Write-Output "Starting $Service service..."
        Start-Service "$Service"
        Write-Output "Done."
    }
}

function StopWindowsService {
    [CmdletBinding()]
    Param
    (
        [string]$Service
    )

    Write-Output "Stopping '$Service' service..."

    try {
        taskkill /F /IM mmc.exe | Out-Null
    }
    catch {}

    if (Get-Service $Service -ErrorAction SilentlyContinue) {
        nssm stop $Service
        Write-Output "Done."
    }
}

function DeleteWindowsService {
    [CmdletBinding()]
    Param
    (
        [string]$Service
    )

    StopWindowsService -Service $Service

    Write-Output "Deleting '$Service' service..."

    if (Get-Service $Service -ErrorAction SilentlyContinue) {
        nssm remove $Service confirm
        Write-Output "Done."
    }
}

function DeleteWindowsServices {
    [CmdletBinding()]
    Param
    (
        [string[]]$Services
    )

    foreach ($service in $Services) {
        DeleteWindowsService -Service $service
    }
}

Export-ModuleMember -Function "NewWindowsService"
Export-ModuleMember -Function "StartWindowsService"
Export-ModuleMember -Function "StopWindowsService"
Export-ModuleMember -Function "DeleteWindowsService"
Export-ModuleMember -Function "DeleteWindowsServices"