Create a service

Description

This example shows how you can use the Service resource to ensure a service exists and is running.

With Ensure set to Present, Name set to Service1, and Path set to C:\FilePath\MyServiceExecutable.exe, the resource creates Service1 if it doesn't exist with MyServiceExecutable.exe as the executable file and starts it.

If Service1 exists but isn't running, the resource starts it.

With Invoke-DscResource

This script shows how you can use the Service resource with the Invoke-DscResource cmdlet to ensure the Service1 service exists with MyServiceExecutable.exe as the executable and is running.

[CmdletBinding()]
param()

begin {
    $SharedParameters = @{
        Name       = 'Service'
        ModuleName = 'PSDscResource'
        Properties = @{
            Name   = 'Service1'
            Ensure = 'Present'
            Path   = 'C:\FilePath\MyServiceExecutable.exe'
        }
    }

    $NonGetProperties = @(
        'Ensure'
        'Path'
    )
}

process {
    $TestResult = Invoke-DscResource -Method Test @SharedParameters

    if ($TestResult.InDesiredState) {
        $QueryParameters = $SharedParameters.Clone()

        foreach ($Property in $NonGetProperties) {
            $QueryParameters.Properties.Remove($Property)
        }

        Invoke-DscResource -Method Get @QueryParameters
    } else {
        Invoke-DscResource -Method Set @SharedParameters
    }
}

With a Configuration

This snippet shows how you can define a Configuration with a Service resource block to ensure the Service1 service exists with MyServiceExecutable.exe as the executable and is running.

Configuration Create {
    Import-DscResource -ModuleName 'PSDscResources'

    Node localhost {
        Service ExampleService {
            Name   = 'Service1'
            Ensure = 'Present'
            Path   = 'C:\FilePath\MyServiceExecutable.exe'
        }
    }
}