Set-ItemProperty sets Registry Value as String on some systems instead of DWord, why?

58,203

Solution 1

I don't have an answer to why it happens but to avoid such instances, be explicit. Use the Type (dynamic) Parameter and specify a RegistryValueKind value (you can also use it with New-ItemProperty) :

Set-ItemProperty -Path HKCR:\Software\MyCompany -Name Level -Value 5 -Type DWord

Solution 2

Try this.

[Microsoft.Win32.Registry]::SetValue("HKEY_CLASSES_ROOT\Software\MyCompany","Level",5,[Microsoft.Win32.RegistryValueKind]::DWord)
Share:
58,203
Erik
Author by

Erik

Updated on July 09, 2022

Comments

  • Erik
    Erik almost 2 years

    I try to create an item using Set-ItemProperty in PowerShell, which works on most systems:

    New-PSDrive -name HKCR -PSProvider Registry -root HKEY_CLASSES_ROOT
    
    Set-ItemProperty -Path HKCR:\Software\MyCompany\ -Name Level -Value 5 -ErrorAction SilentlyContinue 
    

    This creates a DWORD-value on most Windows 7 systems, but I have found one system where this creates a STRING-value instead, and I want to know: why? What could happen that the systems behave differently? All don't have that value already set, all use the same base image using the same Powershell version.

    Btw, I found that by using the following code, I can explicitly set a type, so I already solved the problem:

    New-ItemProperty -Path HKCR:\Software\MyCompany\ -Name Level -Value 5 -ErrorAction SilentlyContinue -PropertyType DWord
    

    But just for curiosity, I want to know why the systems behave differently.

  • Eric Nemchik
    Eric Nemchik over 9 years
    This works well for older powershell versions where for some odd reason the -type parameter doesnt seem to exist.
  • E.V.I.L.
    E.V.I.L. almost 7 years
    Is the -Type documented anywhere?
  • KERR
    KERR about 6 years
    Note that you have to specify the decimal value here instead of the hex value.
  • Maximilian Burszley
    Maximilian Burszley over 5 years
    @MadTomVane It appears to be a registry-provider-specific thing. I couldn't find further documentation but this article was useful for me.
  • user2924019
    user2924019 over 5 years
    "Type" appears to be invalid in Windows 10. Also Colon after "HKCR" is invalid.
  • Cheslab
    Cheslab over 2 years
    If PowerShell gives you an error on -Type try to use path's short form. Instead of HKEY_LOCAL_MACHINE\... try HKLM:\.... Works as of today with Windows 10 v20H2 b19042.1052