Home > Software design >  Setting registry key value from powershell
Setting registry key value from powershell

Time:10-26

When I try to set a registry key from a powershell script it overwrites another key :

For example :

$registryKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Qualys\QualysAgent\ScanOnDemand\Vulnerability"
$valuedata = '1'
$valuename = "Scanondemand"
Set-ItemProperty -Path $registryKey -Name $ValueName -Value $ValueData

This sets registry key right. Then I change the valuename:

$valuename = 'ScanOnstartup'
Set-ItemProperty -Path $registryKey -Name $ValueName -Value $ValueData

On now the Scanonstartup is correct but the Scanondemand key is gone. It kind of renames the name instead of creating a new key.

CodePudding user response:

You may be looking to replace your second add with:

New-ItemProperty

CodePudding user response:

The problem is that you do not specify the PowerShell drive in the registry path.

You can either use the long form:

Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Qualys\QualysAgent\ScanOnDemand\Vulnerability

or make use of the fact that for HKEY_LOCAL_MACHINE PowerShell already has a drive set up by name HKLM:

HKLM:\SOFTWARE\Qualys\QualysAgent\ScanOnDemand\Vulnerability

Your code would then be

$registryKey = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Qualys\QualysAgent\ScanOnDemand\Vulnerability'
# or: $registryKey = 'HKLM:\SOFTWARE\Qualys\QualysAgent\ScanOnDemand\Vulnerability'

$valuedata = '1'
$valuename = 'ScanOnDemand', 'ScanOnStartup'
$null = New-Item $registryKey -Force
Set-ItemProperty -Path $registryKey -Name $ValueName[0] -Value $ValueData
Set-ItemProperty -Path $registryKey -Name $ValueName[1] -Value $ValueData

By using switch -Force to the New-Item cmdlet, you do not have to check if that key already exists because it will return either the existing key as object or the newly created one. Because we have no further use for that object as such, we ignore it with $null = New-Item ..

After running this (as Administrator), you have created this keys structure in the registry:

enter image description here

And in subkey Vulnerability you now have these two entries:

enter image description here

  • Related