Home > Mobile >  Extract root hive from Registry key path
Extract root hive from Registry key path

Time:11-04

Is there a registry equivalent of [System.IO.path]::GetPathRoot($path)? I want to recursively delete empty parent keys after deleting a specified key or property, so I want to walk back up the tree until I reach the root hive. And I would prefer not to just continue until an exception is thrown.

CodePudding user response:

I don't know of a specific function for this.

If you use the registry provider, you can also use the PSDrive property on the child items, which will give you information about the registry root:

(Get-Item "HKLM:\Software\Windows").PSDrive.Name

or

(Get-Item "HKLM:\Software\Windows").PSDrive.Root

Although for "regular" registry paths, it would still be as simple as

$root = $path.Split("\")[0]

As for your specific scenario, you could create a function like this:

function Remove-KeyIfEmpty {
<#
.SYNOPSIS
Removes empty registry keys and optionally empty parent keys recursively.
#>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(
            Mandatory,
            Position = 0,
            ValueFromPipeline,
            ValueFromPipelineByPropertyName
        )]
        [Alias("PSPath")]
        [string]$Path,
        [switch]$Recurse
    )
    $key = Get-Item $Path
    if ($key.Property.Count -eq 0 -and $key.SubKeyCount -eq 0) {
        if ($PSCmdlet.ShouldProcess($key, "Remove-Item")) {
            Remove-Item $Path
            if ($Recurse -and $key.PSParentPath) {
                Remove-KeyIfEmpty $key.PSParentPath -Recurse
            }
        }
    }
}

Example:

Remove-KeyIfEmpty "HKCU:\Software\Example\SubKey" -Recurse

It even supports common parameters, like the -WhatIf, -Confirm, -Verbose and -ErrorAction switches.

  • Related