简体   繁体   English

从 powershell 设置注册表项值

[英]Setting registry key value from powershell

When I try to set a registry key from a powershell script it overwrites another key :当我尝试从 powershell 脚本设置注册表项时,它会覆盖另一个项:

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

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

On now the Scanonstartup is correct but the Scanondemand key is gone.现在Scanonstartup是正确的,但Scanondemand键不见了。 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.问题是您没有在注册表路径中指定 PowerShell驱动器

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:或者利用对于HKEY_LOCAL_MACHINE PowerShell 已经有一个名称为HKLM:的驱动器的事实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.通过对New-Item cmdlet 使用 switch -Force ,您不必检查该键是否已存在,因为它会将现有键作为对象或新创建的键返回。 Because we have no further use for that object as such, we ignore it with $null = New-Item ..因为我们没有进一步使用该对象,所以我们使用$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:在子项Vulnerability您现在有以下两个条目:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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