Windows任务计划程序无法返回PowerShell脚本的$LASTEXITCODE,如何获取正确退出码?
问题分析与解决方案
问题原因
单引号命令的问题
使用单引号包裹-Command参数时:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command '. C:\myscript.ps1; exit $LastExitCode'
Windows的CMD(任务计划通过CMD解析命令行)不识别单引号为引号,会尝试解析$LastExitCode为CMD环境变量(CMD变量格式为%变量名%)。由于不存在名为LastExitCode的CMD环境变量,$LastExitCode会被替换为空字符串,最终PowerShell执行的命令变为:
. C:\myscript.ps1; exit
无参数的exit默认返回0,因此任务计划收到返回码0。
双引号命令的问题
改用双引号后:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command ". C:\myscript.ps1; exit $LastExitCode"
CMD会解析双引号内的$LastExitCode,但同样因CMD不支持$开头的变量格式,导致命令解析异常。返回码2147942401对应Windows系统错误码0x80070001(ERROR_INVALID_FUNCTION),是命令行解析错误导致的结果。
解决方案
方案1:使用-File参数(推荐)
-File是PowerShell专门用于执行脚本的参数,脚本的退出码会直接作为PowerShell进程的退出码传递给任务计划,无需额外处理。
修改后的任务动作命令:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -File "C:\myscript.ps1"
执行后任务计划会收到脚本中Exit 1返回的1。
方案2:转义$符号(保留-Command时使用)
如果必须使用-Command,需要用CMD的转义符^对$进行转义,避免CMD解析$LastExitCode:
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command ". C:\myscript.ps1; exit ^$LastExitCode"
这样PowerShell能正确获取脚本执行后的$LastExitCode,并将其作为进程退出码返回,任务计划就能收到预期的1。
内容的提问来源于stack exchange,提问作者stackleit
相关产品推荐
相关产品推荐

