删除环境变量
说明
此示例演示如何使用 Environment
资源来确保不存在非路径环境变量。
将“确保”Absent
设置为“名称TestEnvironmentVariable
”和“路径”设置为$false
“后,资源将删除调用的环境变量TestEnvironmentVariable
(如果存在)。
将 Target 设置为同时具有两Process
Machine
者的数组,资源将从进程和计算机目标中删除环境变量。
使用 Invoke-DscResource
此脚本演示如何将 Environment
资源与 cmdlet 配合使用 Invoke-DscResource
,以确保 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
}
}
使用配置
此代码片段演示如何使用资源块定义,Configuration
Environment
以确保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'
)
}
}
}