Search code examples
powershellregistry

Set-ItemProperty creates a duplicate registry key


I am trying to activate Long path names in Windows 10 1903.

When I run as administrator in Windows PowerShell :

Set-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -value '1'

I see that a new registry key has been created, instead of overwriting existing one.

enter image description here

Thanks for your help.


Solution

    • There is no reason to assume a bug here - your command should work as intended, but it does the wrong thing (see below).

    • The symptom you show - duplicate value names in a registry key - are inconsistent with the command in your question.

      • The underlying native registry APIs do not allow creating values with duplicate names in a given registry key; if they did - which would be a serious bug - the problem would lie there, not in PowerShell.

      • If the registry editor really shows two values whose names appear to be identical, the only plausible explanation is that they contain invisible characters that makes them different.


    As for what you tried:

    The system-known LongPathsEnabled registry value of key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem is a 64-bit integer, of registry type REG_DWORD, equivalent to a [uint32] instance in .NET / PowerShell.

    By using -Value '1' in your Set-ItemProperty call, you're letting it infer what registry type to write the value as, and that is REG_SZ, i.e. a literal string:

    • However, if the target value already exists, and is of - the correct - type REG_DWORD, PowerShell will convert the string for you.

    • By contrast, if no such value exists yet, you'll - incorrectly - create a REG_SZ value.


    Your own answer now uses -Value 1, which makes the 1 implicitly an [int] (System.Int32), in which case PowerShell correctly infers REG_DWORD.

    However - both for readability and robustness - consider using the -Type parameter to explicitly indicate the type of registry value you're planning to create (command spread across multiple lines for readability - note the ` chars. at the end of the interior lines, which must be the very last char. on their respective lines):

    Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' `
      -Name 'LongPathsEnabled' `
      -Value 1 `
      -Type DWord
    

    The -Type argument is of type Microsoft.Win32.RegistryValueKind, which, when you create or set a value, must be one of the following values (shown here mapped to their REG_* values):

    String        # REG_SZ
    ExpandString  # REG_EXPAND_SZ
    Binary        # REG_BINARY
    DWord         # REG_DWORD
    MultiString   # REG_MULTI_SZ
    QWord         # REG_QWORD
    

    The full list of native REG_* types can be found here.