说明
此示例演示如何使用 WindowsProcess 资源来确保进程未运行,并根据需要使用指定的帐户停止进程。
如果未使用 Credential 参数显式传递凭据,系统会提示输入 凭据 。 资源的 Credential 属性设置为此值。
将 “确保 设置为 Absent”、“ 路径 设置为 C:\Windows\System32\gpresult.exe”和 “参数 ”设置为空字符串时,资源将停止任何正在运行 gpresult.exe 的进程。 由于设置了 Credential 属性,因此资源会停止该帐户的进程。
使用 Invoke-DscResource
此脚本演示如何将 WindowsProcess 资源与 Invoke-DscResource cmdlet 配合使用,以确保 gpresult.exe 未运行,将其作为用户指定的帐户停止。
[CmdletBinding()]
param(
    [ValidateNotNullOrEmpty()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
$Credential = (Get-Credential)
)
begin {
    $SharedParameters = @{
        Name       = 'WindowsFeatureSet'
        ModuleName = 'PSDscResource'
        Properties = @{
            Path       = 'C:\Windows\System32\gpresult.exe'
            Arguments  = ''
            Credential = $Credential
            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
    }
}
使用配置
此代码片段演示如何使用WindowsProcess资源块定义,Configuration以确保gpresult.exe未运行,将其停止为用户指定的帐户。
Configuration StopUnderUser {
    [CmdletBinding()]
    param(
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential = (Get-Credential)
    )
    Import-DSCResource -ModuleName 'PSDscResources'
    Node localhost {
        WindowsProcess ExampleWindowsProcess {
            Path       = 'C:\Windows\System32\gpresult.exe'
            Arguments  = ''
            Credential = $Credential
            Ensure     = 'Absent'
        }
    }
}