共用方式為


移除環境變數

描述

此範例示範如何使用 Environment 資源來確保非路徑環境變數不存在。

[確定] 設定為 、將 [名稱] 設定為 TestEnvironmentVariableAbsent ,並將[路徑] 設定為 $false 時,資源會移除存在時所呼叫 TestEnvironmentVariable 的環境變數。

Target 設定為具有 ProcessMachine 的陣列時,資源會從進程和電腦目標中移除環境變數。

使用 Invoke-DscResource

此腳本示範如何搭配 Invoke-DscResource Cmdlet 使用 Environment 資源,以確保 TestEnvironmentVariable 已從進程和電腦目標中移除。

<#
.SYNOPSIS
.DESCRIPTION
    Removes the environment variable `TestEnvironmentVariable` from both the
    machine and the process.
#>

[CmdletBinding()]
param()

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

    $NonGetProperties = @(
        '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 已從進程和電腦目標中移除。

<#
.SYNOPSIS
.DESCRIPTION
    Removes the environment variable `TestEnvironmentVariable` from both the
    machine and the process.
#>

configuration Sample_Environment_Remove {
    Import-DscResource -ModuleName 'PSDscResources'

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