InstanceCreationPlugins/service-plugin.psm1

#requires -version 4

function ModuleRoot
{
    $MyInvocation.ScriptName | Split-Path -Parent
}
$PrivPath = $(Join-Path $(ModuleRoot | Split-Path -Parent) "\Private")
. $PrivPath\HelperFunctions.ps1

<#
.SYNOPSIS
    Plugin for creating services as defined in the ISPSInstance.config
.DESCRIPTION
    This plugin only acts on nodes with the Name attribute of "Service".
    This element is an instruction to create a regular Windows service.
    Both the executable- and configuration file path is concatenated with the instance directory.
    The service name will be named after the instance name, prepending "IntelliSearch"
    The startup argument is required. If you want to create a service without using a startup argument you can do something similar to this: "{0}{1}"
 
    Example from ISPSInstance.config:
    <Service
        Executable="\bin\someexecutablefile.exe"
        ConfigurationFile="\cfg\someconfigfile.exe.config"
        StartupArgument="{0} --config {1}" />
     
.EXAMPLE
    $Splat = @{
        Node = @{
            Executable = "\bin\someexecutablefile.exe"
            ConfigurationFile = "\cfg\someconfigfile.exe.config"
            StartupArgument = "{0} --config {1}"
        }
        InstanceName = "NameOfService"
        InstanceDirectory = "C:\ProgramData\IntelliSearch\MyInstance\"
        ComponentDirectory "C:\ProgramFiles\IntelliSearch\IntelliSearch.Server.IndexManager.4.0.2\"
    }
    service.plugin @Splat
.PARAMETER Node
    The XML node currently being iterated over
.PARAMETER InstanceName
    A string with the name of the instance. This plugin ignores this parameter.
.PARAMETER InstanceDirectory
    The root directory of the new instance
.PARAMETER ComponentDirectory
    The root directory of the installed component
.INPUTS
    System.String
.OUTPUTS
    System.ServiceProcess.ServiceController
#>

function service-plugin
{
    param (
        # XML node from ISPSInstance.config
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "XML node from ISPSInstance.config")]
        $Node,
    
        # The name representing the new instance
        [Parameter(
            Mandatory = $true,
            Position = 1,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Instance name")]
        [ValidateNotNullOrEmpty()]
        [string] $InstanceName,
        
        # Path to the directory of the new instance
        [Parameter(
            Mandatory = $true,
            Position = 2,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Path to the directory of the new instance")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {Test-Path -Path $_ -PathType Container})]
        [string] $InstanceDirectory,
    
        # Path to the component nuget package directory
        [Parameter(
            Mandatory = $true,
            Position = 3,
            ValueFromPipelineByPropertyName = $true,
            HelpMessage = "Path to the component nuget package directory")]
        [ValidateNotNullOrEmpty()]
        [ValidateScript( {Test-Path -Path $_ -PathType Container})]
        [string] $ComponentDirectory
    )

    if ($Node.Name -ne "Service")
    {
        return
    }

    $BinaryPath = Join-Path $ComponentDirectory $Node.Executable
    $ConfigPath = Join-Path $InstanceDirectory $Node.ConfigurationFile
    $ServiceName = "IntelliSearch " + $InstanceName

    #region Validation
    $Errors = New-Object System.Collections.ArrayList

    if (-not (ValidatePathExists $BinaryPath))
    {
        $Errors.Add("Path to binary file not valid. Got $BinaryPath")
    }

    if (-not (ValidatePathExists $ConfigPath))
    {
        $Errors.Add("Path to configuration file not valid. Got $ConfigPath")
    }

    if (-not (ValidateServiceName $ServiceName))
    {
        $Errors.Add("Service name is not valid. Got $ServiceName")
    }

    if (-not (ValidateServiceUnique $ServiceName))
    {
        $Errors.Add("Service name is not unique. Another service has the same name. Got $ServiceName")
    }

    if (-not (ValidateStartupArgument $Node.StartupArgument))
    {
        $Errors.Add("The startup argument from the ISPSInstance.config file was not valid. Got $($Node.StartupArgument)")
    }

    if ($Errors.Count -gt 0)
    {
        $ErrorMessage = "$($Errors.Count) errors were found creating the service.`n" + ($Errors -Join "`n")
        Throw $ErrorMessage
    }
    #endregion Validation

    $ServiceSplat = @{
        Name           = $ServiceName
        BinaryPathName = $Node.StartupArgument -f $BinaryPath, $ConfigPath
        DisplayName    = $ServiceName
        StartupType    = "Automatic"
    }

    New-Service @ServiceSplat
}

Export-ModuleMember -Function "service-plugin"

function ValidateServiceName ($ServiceName)
{
    # Validates that the service name consists of allowed characters
    return [bool]($ServiceName -Match "^[\w\-_()\. ]+$")
}

function ValidateServiceUnique ($ServiceName)
{
    # Validates that the service name is unique
    return -not [bool](Get-Service -Name $ServiceName -ErrorAction:SilentlyContinue)
}

function ValidateStartupArgument ($ArgumentString)
{
    # Validates startup argument for service
    return [bool]($ArgumentString -Match ".*\{0\}.*\{1\}.*")
}