windows 如何获取批处理脚本的任务计划程序上次运行结果退出代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6791115/
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 17:33:13  来源:igfitidea点击:

How do I get Task Scheduler Last Run Result exit code for batch script?

windowsbatch-filetaskscheduler

提问by John Smith

I need to know if the task ran successfully so I can create an event in the Application log saying so. Is there a way to get this in code? I tried the following:

我需要知道任务是否成功运行,以便我可以在应用程序日志中创建一个事件。有没有办法在代码中得到这个?我尝试了以下方法:

echo ErrorLevel of "c:\windows\system32\tasks\my task" = %ErrorLevel%

But I get 0 every time, even if I stop it prematurely (0x41306) or while the task is still running (should be 0x41301). Does anyone have any ideas? Thank you.

但是我每次都得到 0,即使我过早停止(0x41306)或在任务仍在运行时(应该是 0x41301)。有没有人有任何想法?谢谢你。

I found a workaround to this. Instead of getting the exit code of the task, I got the exit code of the batch script that actually runs and if it's anything but 0 then I make an error application event, otherwise it's a success application event.

我找到了一个解决方法。我没有获得任务的退出代码,而是获得了实际运行的批处理脚本的退出代码,如果它不是 0,那么我将创建一个错误应用程序事件,否则它是一个成功应用程序事件。

回答by Devil's Advocate

The following batch file accepts a parameter of a task name, for instance if you named the bat file "getresult.bat" you would call "getresult GoogleUpdateTaskMachineCore" (If the name has spaces, put quotes around it).

以下批处理文件接受任务名称的参数,例如,如果您将 bat 文件命名为“getresult.bat”,您将调用“getresult GoogleUpdateTaskMachineCore”(如果名称有空格,请在其周围加上引号)。

This is very verbose, so let me know if you need help adapting it to fit your needs.

这是非常冗长的,所以如果您需要帮助调整它以满足您的需求,请告诉我。

Tested and working in Windows 8, I believe it should work for XP/Vista/7 as well.

在 Windows 8 中测试和工作,我相信它也应该适用于 XP/Vista/7。

@ECHO OFF

IF %1=="" GOTO EXITNOINPUT

ECHO Checking Tasks for "%1"...

FOR /F "tokens=2delims=:" %%I IN ('schtasks /tn %1 /fo LIST /v ^| FIND "Last Result"') DO (
    SET result=%%I
)

IF NOT DEFINED result GOTO EXITNOTFOUND

ECHO Done...
ECHO The Last Result Was:  %result%

GOTO EXITNORMAL

:EXITNOTFOUND
echo The scheduled task was not found.
GOTO EXITNORMAL


:EXITNOINPUT
echo You must provide a query. (getresult servicename)
GOTO EXITNORMAL

:EXITNORMAL