代码用FOR语句的`IN`参数中的单引号包装为命令不起作用

时间:2017-09-01 10:13:44

标签: windows batch-file cmd

在我的Windows PC上,系统没有将FOR语句的IN参数中包含在单引号中的代码作为命令。

请考虑以下代码。

FOR /F "delims=" %F IN ('dir *') DO (echo %F)

输出

'dir *' is not recognized as an internal or external command, operable program or batch file.

在这里您可以看到系统没有将dir \b作为命令,而是尝试执行'dir \b *',即包括引用。哪一整不是命令。

我正在使用Windows 7.相同的代码正在其他Windows PC上运行。我无法弄清楚这在我的机器上运行会有什么不同。

1 个答案:

答案 0 :(得分:2)

检查ComSpec变量的值。命令解释程序使用它来执行内部命令。如果它不是cmd.exe,您将收到该错误消息:

C:\Users\klitos>set comspec=xxx

C:\Users\klitos>for /f "delims=" %f in ('dir') do @echo %f-
'dir' is not recognized as an internal or external command,
operable program or batch file.

修复它:

C:\Users\klitos>set comspec=C:\Windows\System32\cmd.exe

C:\Users\klitos>cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\klitos>for /f "delims=" %f in ('dir') do @echo %f-
 Volume in drive C is OS-

一旦您确定了将comspec设置为错误值的恶意代码,请将其修复为永久解决方案。