在 Windows 上使用带有 for /f 的管道命令(使用 reg 查询)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8412149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:36:46  来源:igfitidea点击:

using piped commands with for /f on windows (with reg query)

windowsbatch-fileregistry

提问by Rex

I am trying to query the install location of a program in the registry. All I'm interested in is the location output.

我正在尝试在注册表中查询程序的安装位置。我感兴趣的只是位置输出。

This questionhas a partial solution, but it doesn't quite help. On Windows 7, the reg command outputs a stupid registry key header along with the value, as shown below:

这个问题有一个部分解决方案,但它并没有多大帮助。在 Windows 7 上,reg 命令输出一个愚蠢的注册表项标头以及值,如下所示:

reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode" /v InstallLocation

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode
InstallLocation    REG_EXPAND_SZ    C:\Program Files\NSIS

First, is there a way to turn off the header and simplify the output?

首先,有没有办法关闭标题并简化输出?

At the command prompt, I can change the above to

在命令提示符下,我可以将上面的更改为

reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode" /v InstallLocation | findstr InstallLocation

so that it returns me just the second line.

以便它只返回第二行。

Now, if I am to use a FOR /Fto parse this and get only the directory value, the FORcommand fails saying | was unexpected at this time.

现在,如果我要使用 aFOR /F来解析它并仅获取目录值,则该FOR命令将无法显示| was unexpected at this time.

Here's my batch file:

这是我的批处理文件:

@for /f "tokens=2* delims=   " %%k in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode" /v InstallLocation | findstr InstallLocation') do @echo %%k

So where am I going wrong?

那么我哪里出错了?

回答by Tomalak

You must escape the |character using a caret (^).

您必须|使用插入符号 ( ^)对字符进行转义。

@echo off
setlocal

set KEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode
set V=InstallLocation

for /f "tokens=2* delims= " %%k in ('reg query "%KEY%" /v %V% ^| findstr "%V%"') do echo %%k

this would return REG_SZon my machine.

这将返回REG_SZ到我的机器上。

回答by Matej

The pipe char is special and has to be escaped with ^.

管道字符是特殊的,必须用^.

@for /f "tokens=2* delims=   " %%k in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NSIS Unicode" /v InstallLocation ^| findstr InstallLocation') do @echo %%k