如何用reg query检查含%SystemRoot%的PowerShell注册表项是否存在?
解决注册表路径中%SystemRoot%的转义问题
要让reg query识别路径中的%SystemRoot%为字面量而非环境变量,需根据使用环境选择对应转义方式:
1. CMD命令行环境
直接在CMD窗口执行命令时,用^(脱字符)转义每个%,阻止环境变量被自动展开:
reg query "HKCU\Console\^%SystemRoot^%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit
如果要将QuickEdit值设为0禁用快速编辑,执行:
reg add "HKCU\Console\^%SystemRoot^%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit /t REG_DWORD /d 0 /f
2. CMD批处理文件环境
在.bat/.cmd脚本中,用两个%转义单个%,批处理解析时会保留字面量的%SystemRoot%:
@echo off reg query "HKCU\Console\%%SystemRoot%%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit reg add "HKCU\Console\%%SystemRoot%%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit /t REG_DWORD /d 0 /f
3. PowerShell环境
PowerShell中两种方式可实现需求:
方法一:单引号包裹路径
单引号内的内容不会被解析为变量或环境变量,直接保留字面量:
reg query 'HKCU\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe' /v QuickEdit reg add 'HKCU\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe' /v QuickEdit /t REG_DWORD /d 0 /f
方法二:反引号转义%
用`(反引号)转义每个%,强制保留字面量:
reg query "HKCU\Console\`%SystemRoot`%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit reg add "HKCU\Console\`%SystemRoot`%_System32_WindowsPowerShell_v1.0_powershell.exe" /v QuickEdit /t REG_DWORD /d 0 /f
为什么%%SystemRoot%%在命令行中无效?
在CMD命令行中,输入%%会被解析为单个%,最终路径变为%SystemRoot%,CMD仍会自动展开这个环境变量,导致路径匹配失败。只有在批处理文件中,%%才会被正确保留为字面量的%。
内容的提问来源于stack exchange,提问作者MTV
相关产品推荐
相关产品推荐

