![](/img/trans.png)
[英]rm binary in Windows $PATH but Powershell still prefers Remove-Item
[英]PowerShell - How can I use regex in the middle of registry file path to perform remove-item operation?
我看过很多类似的问题并尝试了很多东西,但我无法让它发挥作用。
$Regex = 'RegexPattern'
Remove-Item -Path 'HKCU:System\somePath\' + $Regex + '\MorePath\*' -Recurse
Remove-Item -Path "HKCU:System\somePath\$Regex\MorePath\*" -Recurse
Remove-Item -Path "HKCU:System\somePath\$($Regex)\MorePath\*" -Recurse
Remove-Item -Path "HKCU:System\somePath\'RegexPattern'\MorePath\*" -Recurse
Remove-Item -Path 'HKCU:System\somePath\"RegexPattern"\MorePath\*' -Recurse
这些都不起作用。
我有一个正则表达式,只想删除带有 remove-item 的文件夹的子项,但我不知道如何让它解析正则表达式而不是从字面上理解模式。
要应用正则表达式匹配,请使用Get-ChildItem
,使用Where-Object
过滤结果,这允许您使用-match
运算符执行正则表达式匹配,并将Remove-Item
应用于结果; 沿着以下几行:
Get-ChildItem -Path HKCU:\System\somePath\*\MorePath |
Where-Object Name -match $RegexPattern |
Remove-Item -Recurse -WhatIf
注意:上面命令中的-WhatIf
公共参数可以预览操作。 删除-WhatIf
并在您确定操作将执行您想要的操作后重新执行。
笔记:
上面使用通配符*
来匹配潜在兴趣的键,稍后通过正则表达式进行过滤; 根据需要调整。
由于您正在处理注册表项,因此.Name
指的是完整的注册表本机密钥路径,例如HKEY_CURRENT_USER\System\...
,假定Get-ChildItem
的注册表项 output 表示为[Microsoft.Win32.RegistryKey]
实例。
Where-Object
调用使用简化的语法,在像这样的简单情况下可以使用更简洁的语法; 它等效于以下内容:
Where-Object { $_.Name -match $RegexPattern }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.