How to fix Windows batch file FOR command returing “Active code page: 65001”

会有一股神秘感。 提交于 2019-12-11 13:46:10

问题


If I understand correctly this batch script

for /f "usebackq tokens=*" %%i in (`time /t`) do (
  echo "%%i"
)
echo "done"

should just print the time and then "done"

Instead though on my machine, Windows 10 Pro x64 it prints

>test.bat
>for /F "usebackq tokens=*" %i in (`time /t`) do (echo "%i" )
>(echo "Active code page: 65001" )
"Active code page: 65001"
>(echo "17:48" )
"17:48"
>echo "done"
"done"

Why is it doing this and how do I fix it so it just gets the time and not this "Active code page: 65001" result. This is breaking build scripts as it doesn't matter what command goes in the FOR command the first line is always "Active code page: 65001"

To be clear I'm looking for an OS setting fix, not a fix to the batch file. The real batch files I'm trying to run are from build scripts in open source projects and they are failing because of this issue.


回答1:


When we run a command and we get the correct output, but it is preceded by the output of another command, somehow this unexpected command is run before our intended command.

The usual suspect is a batch file created with the same name that the command we are calling, but in this case, being time an internal command, this can not be the case, internal commands have precedence over external commands (default behaviour).

If time is an internal command, how can another command being called?

When for /f needs to process the output of a command a separate cmd instance is created to execute that command. The output generated in this separate instance is processed by the code in the do clause of the for /f command.

The creation of this separate instance can be the source of the unexpected output.

Reading the help information shown by cmd /? we can see that there are two registry keys

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun

that can be configured to run commands every time a new cmd instance is created (unless the /D switch is used when starting the cmd instance).

This is the most probable place where to find why you get the Active code page: 65001 output.



来源:https://stackoverflow.com/questions/48183570/how-to-fix-windows-batch-file-for-command-returing-active-code-page-65001

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!