为什么“where”命令对于完整路径不能按预期工作?

为什么“where”命令对于完整路径不能按预期工作?

仔细阅读这些命令和输出:

where pg_ctl
C:\Program Files\PostgreSQL\12\bin\pg_ctl.exe

where pg_ctl.exe
C:\Program Files\PostgreSQL\12\bin\pg_ctl.exe

where "C:\Program Files\PostgreSQL\12\bin\pg_ctl.exe"
ERROR: Invalid pattern is specified in "path:pattern".

为什么最后一个返回错误而不是输出自身/成功?

我必须能够可靠地输入任何一个该命令的“命令”或可执行文件的完整路径,以确定它是否是可执行命令。

检查错误代码,我得到以下信息:

0
0
2

where /?

NOTE: The tool returns an error level of 0 if the search is
    successful, of 1 if the search is unsuccessful and
    of 2 for failures or errors.

换句话说,它不会为最后一个命令(完整路径)返回正确的 1(搜索失败),而是返回 2(失败或错误)。但即使它确实返回 1 作为退出代码,那仍然是错误的。它应该返回 0,因为路径存在,所以它是一个可执行命令。

答案1

Where 是查找文件的命令。如果指定其完整路径,那么使用 where 有什么意义?

您可以随时使用

if exist c:\path\filename.ext echo File does exist.

但如果您确实想使用 where 命令,请按照其预期用途使用它。使用 /r 参数指定路径,并将要搜索的命令作为单独的参数。

就像这样:

C:\>where /r "C:\Program Files\PostgreSQL\12\bin" pg_ctl.exe
C:\Program Files\PostgreSQL\12\bin\pg_ctl.exe

C:\>_

答案2

线索就在信息中ERROR: Invalid pattern is specified in "path:pattern".

C:\Users>where /?

WHERE [/R dir] [/Q] [/F] [/T] pattern...
[...]
    pattern  Specifies the search pattern for the files to match.
             Wildcards * and ? can be used in the pattern. The
             "$env:pattern" and "path:pattern" formats can also be
             specified, where "env" is an environment variable and
             the search is done in the specified paths of the "env"
             environment variable. These formats should not be used
             with /R. The search is also done by appending the
             extensions of the PATHEXT variable to the pattern.
[...]

Examples:
[...]
    WHERE "c:\windows;c:\windows\system32:*.dll"

正如您所看到的,搜索模式单个通配符匹配,并带有可选的环境变量或搜索路径。由于您传递的是路径,因此它会期望另一个路径:后跟模式。找不到该模式,因此会出现错误

尽管如上所述,如果你已经有了完整路径,那么使用就没有意义了where

相关内容