仅当注册表中的 DWORD32 值已存在时才为其设置值 |电源外壳

Set a value for a DWORD32 value in the registry only if it already exists | PowerShell

我只想在注册表中为 DWORD32 值设置一个值,前提是它已经存在。

这是我的代码:

Set-ItemProperty -Path $mypath -Name $myname -Value 0

此代码的问题出在 Set-ItemProperty class;它创建 DWORD32 值,即使它不存在,我只想在它存在时更改它的值。

有什么解决办法吗?

检查是否 Get-ItemPropertyValue returns any success output while ignoring any errors (in PSv4-, use Get-ItemProperty):

if ($null -ne (Get-ItemPropertyValue -ErrorAction Ignore -LiteralPath $mypath -Name $myname)) {
  Set-ItemProperty -LiteralPath $mypath -Name $myname -Value 0
}

注:

  • 上面只是测试是否注册表值存在——它不检查它的数据类型。对于后者,您可以使用(Microsoft.Win32.RegistryKey.GetValueKind() is of type Microsoft.Win32.RegistryValueKind 返回的值):

    (Get-Item -LiteralPath $path).GetValueKind($myName) -eq 'Dword'
    
  • 请注意,在这种情况下,使用 Test-Path 不是 一个选项,因为它只能测试提供者 项目(映射到注册表 keys),而不是它们的 properties(映射到注册表 values).