使用Where-Object过滤和删除注册表值

Vim*_*mes 4 registry powershell

我不知道为什么我发现这么难.从特定的注册表项下,我想根据数据(而不是名称)查询某些注册表值,并删除生成的注册表值.

例如:

注册表的截图

如何删除此键中包含的任何值,例如"foo".我可以列出注册表值Get-ItemProperty 'HKCU:\Software\Policies\Google\Chrome\RestoreOnStartupURLs',但它将一些垃圾与实际数据混合在一起:

1            : http://foo.example.com
2            : http://bar.example.com
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Policies\Google\Chrome\RestoreOnStartupURLs
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\Software\Policies\Google\Chrome
PSChildName  : RestoreOnStartupURLs
PSDrive      : HKCU
PSProvider   : Microsoft.PowerShell.Core\Registry
Run Code Online (Sandbox Code Playgroud)

我试图管道Where-Object但无法找到有效的查询.然后我需要一个Remove-可以处理结果的cmdlet.有人有主意吗?

The*_*ian 6

我认为这个问题是退后一步,看一看大局.你专注于价值或财产,以及如何获得你没有考虑该属性只是一个更大的对象的一部分的属性名称,关键.让我们使用密钥的对象,看看它在哪里得到我们.我将把路径分配给变量,因为我们稍后会使用它.

$KeyPath = 'HKCU:\Software\Policies\Google\Chrome\RestoreOnStartupURLs'
$ChromeKey = Get-Item $KeyPath
Run Code Online (Sandbox Code Playgroud)

现在该对象是Microsoft.Win32.RegistryKey对象,内置了一些有用的方法.我们关注的是你需要的那个GetValueNames(),它(不出所料)给你了值的名称,你应该返回:

(default)
1
2
Run Code Online (Sandbox Code Playgroud)

因此,我们将其输入到一个Where语句中,该语句获取这些名称的实际值,将它们与Foo匹配,然后我们对它们进行操作.首先,获取我们关注的那些属性:

$ChromeKey.GetValueNames() | Where {$ChromeKey.GetValue($_) -match "foo"}
Run Code Online (Sandbox Code Playgroud)

该命令应该返回一个值,1.然后根据需要使用像Remove-ItemProperty这样的东西......

$ChromeKey.GetValueNames() | Where {$ChromeKey.GetValue($_) -match "foo"} | ForEach{ Remove-ItemProperty -Path $KeyPath -Name $_ }
Run Code Online (Sandbox Code Playgroud)

完成后,会找到与"foo"匹配的键的所有值,并将其从键中删除.