Remove an environment variable
Description
This example shows how you can use the Environment
resource to ensure a non-path environment
variable doesn't exist.
With Ensure set to Absent
, Name set to TestEnvironmentVariable
, and Path set to
$false
, the resource removes the environment variable called TestEnvironmentVariable
if it
exists.
With Target set to an array with both Process
and Machine
, the resource removes the
environment variable from both the process and machine targets.
With Invoke-DscResource
This script shows how you can use the Environment
resource with the Invoke-DscResource
cmdlet to
ensure TestEnvironmentVariable
is removed from the process and machine targets.
<#
.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
}
}
With a Configuration
This snippet shows how you can define a Configuration
with an Environment
resource block to
ensure TestEnvironmentVariable
is removed from the process and machine targets.
<#
.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'
)
}
}
}
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for