我正在使用一个划线员根据值查找注册表项,然后删除其父项。一个内衬会产生错误,但是如果我将搜索结果分成一个变量并运行remove-item,则不会出错。我想找出造成这种情况的原因,如果我担心的话?
产生错误:
Get-ChildItem -path HKLM:\SOFTWARE\Classes\Installer\Products -Recurse -ErrorAction Stop | Get-ItemProperty -Name "PackageName" -ErrorAction SilentlyContinue| where { $_.PackageName -cmatch "BigFixAgent\.msi" } | Select-Object -ExpandProperty PSParentPath | Remove-Item -Recurse -confirm
Get-ChildItem : The registry key at the specified path does not exist. At line:1 char:1 + Get-ChildItem -path HKLM:\SOFTWARE\Classes\Installer\Products -Recurs ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (HKEY_LOCAL_MACH...4D34\SourceList:String) [Get-ChildItem], ArgumentException + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.GetChildItemCommand
不产生错误:
$offending_key= Get-ChildItem -path HKLM:\SOFTWARE\Classes\Installer\Products -Recurse -ErrorAction Stop | Get-ItemProperty -Name "PackageName" -ErrorAction SilentlyContinue| where { $_.PackageName -cmatch "BigFixAgent\.msi" } | Select-Object -ExpandProperty PSParentPath
Remove-Item -Recurse $offending_key -confirm
答案 0 :(得分:0)
那是因为它正在注册表树中递归地进行迭代,并且您在迭代的中间删除了该树的一部分。您可以在除最后一部分之外的所有内容上加上括号,以使其首先完成迭代,也可以将最后一部分放入ForEach-Object
循环中,并在其后添加一个分隔符,以便一旦找到该键就将其删除并停止寻找。
在删除前完成Get-ChildItem
迭代:
(Get-ChildItem -path HKLM:\SOFTWARE\Classes\Installer\Products -Recurse -ErrorAction Stop | Get-ItemProperty -Name "PackageName" -ErrorAction SilentlyContinue| where { $_.PackageName -cmatch "BigFixAgent\.msi" } | Select-Object -ExpandProperty PSParentPath) | Remove-Item -Recurse -confirm
找到第一个匹配键后停止:
Get-ChildItem -path HKLM:\SOFTWARE\Classes\Installer\Products -Recurse -ErrorAction Stop | Get-ItemProperty -Name "PackageName" -ErrorAction SilentlyContinue| where { $_.PackageName -cmatch "BigFixAgent\.msi" } | Select-Object -ExpandProperty PSParentPath | ForEach-Object {$_ | Remove-Item -Recurse -confirm; break}