是否有等效于的注冊表[System.IO.path]::GetPathRoot($path)?我想在洗掉指定的鍵或屬性后遞回洗掉空的父鍵,所以我想回到樹上,直到到達根配置單元。而且我不希望在拋出例外之前繼續。
uj5u.com熱心網友回復:
我不知道這個的具體功能。
如果您使用注冊表提供程式,您還可以PSDrive在子項上使用該屬性,這將為您提供有關注冊表根的資訊:
(Get-Item "HKLM:\Software\Windows").PSDrive.Name
或者
(Get-Item "HKLM:\Software\Windows").PSDrive.Root
盡管對于“常規”注冊表路徑,它仍然很簡單
$root = $path.Split("\")[0]
至于您的特定場景,您可以創建這樣的函式:
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
}
}
}
}
例子:
Remove-KeyIfEmpty "HKCU:\Software\Example\SubKey" -Recurse
它甚至還支持常見的引數,如-WhatIf,-Confirm,-Verbose和-ErrorAction開關。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347540.html
