移除環境變數
描述
此範例示範如何使用 Environment
資源來確保非路徑環境變數不存在。
將[確定] 設定為 、將 [名稱] 設定為 TestEnvironmentVariable
Absent
,並將[路徑] 設定為 $false
時,資源會移除存在時所呼叫 TestEnvironmentVariable
的環境變數。
將 Target 設定為具有 Process
和 Machine
的陣列時,資源會從進程和電腦目標中移除環境變數。
使用 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
}
}
使用組態
此程式碼片段示範如何使用資源區塊來定義 , 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'
)
}
}
}
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應