创建非路径环境变量

说明

此示例演示如何使用 Environment 资源来确保存在具有特定值的非路径环境变量。

“确保”设置为Present名称TestEnvironmentVariable”和“”设置为TestValue“时,资源将添加一个环境变量,如果该值不存在,则TestValue添加一个环境变量TestEnvironmentVariable

With Path set to $false, if TestEnvironmentVariable exists with any value other than TestValue, the resource sets it to exactly TestValue.

Target 设置为同时具有两ProcessMachine者的数组,资源在进程和计算机目标中创建或设置环境变量。

使用 Invoke-DscResource

此脚本演示如何将 Environment 资源与 cmdlet 配合使用 Invoke-DscResource ,以确保 TestEnvironmentVariable 在进程和计算机目标中设置为 TestValue a0/>。

[CmdletBinding()]
param()

begin {
    $SharedParameters = @{
        Name       = 'Environment'
        ModuleName = 'PSDscResource'
        Properties = @{
            Name   = 'TestEnvironmentVariable'
            Value  = 'TestValue'
            Ensure = 'Present'
            Path   = $false
            Target = @(
                'Process'
                'Machine'
            )
        }
    }

    $NonGetProperties = @(
        'Value'
        'Path'
        '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
    }
}

使用配置

此代码片段演示如何使用资源块定义,ConfigurationEnvironment以确保TestEnvironmentVariable在进程和计算机目标中设置为 TestValue

Configuration CreateNonPathVariable  {
    Import-DscResource -ModuleName 'PSDscResources'

    Node localhost {
        Environment ExampleEnvironment {
            Name   = 'TestEnvironmentVariable'
            Value  = 'TestValue'
            Ensure = 'Present'
            Path   = $false
            Target = @(
                'Process'
                'Machine'
            )
        }
    }
}