批处理命令不返回预期路径

时间:2011-03-21 18:31:55

标签: batch-file

Windows中的FOR命令有一些它在DOS中没有的选项。具体来说,它支持返回文件名段,如下所示。

  In addition, substitution of FOR variable references has been enhanced.
  You can now use the following optional syntax:

  %~I         - expands %I removing any surrounding quotes (")
  %~fI        - expands %I to a fully qualified path name
  %~dI        - expands %I to a drive letter only
  %~pI        - expands %I to a path only
  %~nI        - expands %I to a file name only
  %~xI        - expands %I to a file extension only
  %~sI        - expanded path contains short names only
  %~aI        - expands %I to file attributes of file
  %~tI        - expands %I to date/time of file
  %~zI        - expands %I to size of file


当我尝试使用以下命令时,它不起作用。它不打印\Program Files,而是打印\

  for %i in ("%programfiles%") do echo %~pi


似乎只有p参数不正确,因为其他参数会返回预期的结果。

  > for %i in ("%programfiles%") do echo %i
  C:\Program Files

  > for %i in ("%programfiles%") do echo %~i
  C:\Program Files

  > for %i in ("%programfiles%") do echo %~fi
  C:\Program Files

  > for %i in ("%programfiles%") do echo %~is
  C:\PROGRA~1

  > for %i in ("%programfiles%") do echo %~id
  C:


有谁知道问题可能是什么?

2 个答案:

答案 0 :(得分:2)

这不是问题,这是正确的预期结果。 ~p提取给定filespec的路径部分。

在这种情况下

  • c:是由%~di返回的驱动器;
  • \是由%~pi返回的路径;
  • Program Files是由%~ni返回的名称;
  • C:\Program Files是完整的展开文件规范,由%~fi%~dpnxi返回。

答案 1 :(得分:0)

%~pI - expands %I to a path only

但它假设%I是路径+文件名,因此它删除了最后一个组件。

我用文件C:\temp\two\myFile.txt

测试了它

for %% I in(“c:\ temp \ two \ myFile.txt”)做echo%~pI
显示\temp\two\

但仅限于路径
for %% I in(“c:\ temp \ two”)做echo%~pI
它只显示`\ temp \'

但如果最后有一个\ for %% I in(“c:\ temp \ two”)做echo%~pI
它再次显示\temp\two\