简体   繁体   中英

Setting registry key value from powershell

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.

You may be looking to replace your second add with:

New-ItemProperty

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:

在此处输入图片说明

And in subkey Vulnerability you now have these two entries:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM