Search code examples
powershellregistry

Find and Modify Registry values based on Subkey Name


Finding this PowerShell script difficult:

Pic of my registry

|
|__SyncRootManager
  |
  |____OneDrive!S-1-5-21-SID
  |          |_____UserSyncRoots
  |
  |____OneDrive!S-1-5-21-SID
             |_____UserSyncRoots

For every subkey called "UserSyncRoots" that is a child of OneDrive!S-1-5-21-SID (which are children of "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager"), it contains just one Reg Value that is named "S-1-5-21-SID" - how would I modify each Reg Value to "C:\AnyOldPath"

I was using Get-ChildItem in a foreach loop but I think I am going down the wrong path completely. Thank you for any help you can give.

Edit, oops, forgot to add my code

$registry = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager" -Recurse
Foreach($a in $registry) {
    if ( $a.PSChildName -eq "UserSyncRoots" )
    {
        $subkeys = (Get-ItemProperty $a.pspath)
        #Get-ItemProperty - OK I'm lost here
    }
}

Solution

  • Untested (don't have those keys), but assuming no permissions issues, this should work or be close:


    Edited 1/31/24 : Added filtering on ProviderName, removed hard-coded string from processing and replaced with variable, and modified some variable naems.


    ###   Good idea to use single quotes unless string expansion is needed
    $SyncMgrPath     = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager'
    # adding regex for -Match filtering
    $ProviderFilter  = '\\OneDrive\![\d\-]+$'  # <backSlash>OneDrive!<digitsAndDashes><endOfLine>
    $TargetKey       = 'UserSyncRoots'
    $NewValue        = 'C:\AnyOldPath'
    
    Get-ChildItem $SyncMgrPath -Recurse |
      where PSParentPath -match $ProviderFilter |
        where PSChildName -eq $TargetKey |
    ForEach-Object {
        $splat = @{
            'Path'  = $_.PSPath
            'Name'  = $_.Property[0]
            'Value' = $NewValue
            'Type'  = 'String'
        }
        Set-ItemProperty  @splat
    }
    

    Note that (based on your question) there is no testing for the entry's existence or current value -- if it exists, its value is changed, if it doesn't exist, it's created.

    • Registry value types
      • Optional for strings and integers (DWORD), but necessary for other types.
      • Valid values
        • Binary
        • ExpandString
        • MultiString
        • None
        • QWord
        • String
        • Unknown