Add a registry key
Description
This example shows how you can use the Registry
resource to ensure a registry key exists.
With Ensure set to Present
, ValueName set to an empty string, and Key set to
HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\MyNewKey
, the resource adds the
MyNewKey
registry key if it doesn't exist.
With Invoke-DscResource
This script shows how you can use the Registry
resource with the Invoke-DscResource
cmdlet to
ensure the MyNewKey
registry key exists.
[CmdletBinding()]
param()
begin {
$SharedParameters = @{
Name = 'Registry'
ModuleName = 'PSDscResource'
Properties = @{
Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\MyNewKey'
Ensure = 'Present'
ValueName = ''
}
}
$NonGetProperties = @(
'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 a Registry
resource block to ensure
the MyNewKey
registry key exists.
Configuration AddKey {
Import-DscResource -ModuleName 'PSDscResources'
Node localhost {
Registry ExampleRegistry {
Key = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\MyNewKey'
Ensure = 'Present'
ValueName = ''
}
}
}
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.