powershellregistry

Cannot map HKU registry hive with powershell


I have a question regarding deleting from registry key HKU (HKEY_USERS). If I run this with powershell, I get an error:

Invoke-Command -ComputerName $inputPC -ScriptBlock { Remove-Item -Path 'HKU:\S-1-5-25\Software\Microsoft\Windows\CurrentVersion\RunOnce'}

The error:

Cannot find drive. A drive with the name 'HKU' does not exist.
    + CategoryInfo          : ObjectNotFound: (HKU:String) [Remove-Item], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
    + PSComputerName        : clt64792

But if for HKU: I exchange it for example to HKLM: it works and deletes the registry key, how can I access the HKU? I have tried different approaches to delete registry keys and all work the same, but none of them maps the HKU registry key.


Solution

  • By default, only the following PowerShell drives referencing registry locations are defined:

    PS> Get-PSDrive -PSProvider Registry
    
    Name           Used (GB)     Free (GB) Provider      Root                                                                                                           CurrentLocation
    ----           ---------     --------- --------      ----                                                                                                           ---------------
    HKCU                                   Registry      HKEY_CURRENT_USER                                                                                                             
    HKLM                                   Registry      HKEY_LOCAL_MACHINE                                                                                                            
    

    That is, only drives HKCU: and HKLM: exist by default.


    In order to access keys in the HKEY_USERS hive, you have two options:

    # Define drive HKU:
    New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
    # Now you can use HKU:\... paths
    
    # E.g.
    Get-ChildItem registry::HKEY_USERS\.DEFAULT
    

    In the context of your command:

    Invoke-Command -ComputerName $inputPC -ScriptBlock { 
      Remove-Item 'registry::HKEY_USERS\S-1-5-25\Software\Microsoft\Windows\CurrentVersion\RunOnce'
    }