删除服务

说明

此示例演示如何使用 Service 资源来确保服务不存在。

“确保 ”设置为 Absent “和” 名称 “设置为 Service1时,资源将删除 Service1 服务(如果存在)。 如果 Service1 正在运行,资源会 Service1 停止,然后再将其删除。

使用 Invoke-DscResource

此脚本演示如何将 Service 资源与 cmdlet 配合使用 Invoke-DscResource ,以确保 Service1 服务不存在。

[CmdletBinding()]
param()

begin {
    $SharedParameters = @{
        Name       = 'Service'
        ModuleName = 'PSDscResource'
        Properties = @{
            Name   = 'Service1'
            Ensure = 'Absent'
        }
    }

    $NonGetProperties = @(
        'Ensure'
    )
}

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
    }
}

使用配置

此代码片段演示如何使用Service资源块定义,Configuration以确保Service1服务不存在。

Configuration Delete {
    Import-DscResource -ModuleName 'PSDscResources'

    Node localhost {
        Service ExampleService {
            Name   = 'Service1'
            Ensure = 'Absent'
        }
    }
}