繁体   English   中英

Windows 任务计划程序未从 Powershell 脚本返回 $LASTEXITCODE

[英]Windows Task Scheduler not returning $LASTEXITCODE from a Powershell script

我有一个只调用Exit 1的脚本。 但是,当此脚本通过 Windows 任务计划程序运行时,我得到返回码02147942401 ,但我从未得到预期的1 详情如下。

脚本内容

Exit 1

Windows 任务定义:

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command '. C:\myscript.ps1; exit $LastExitCode'

运行结果

当我运行此任务时,任务历史记录显示, Task Scheduler successfully completed task "\My task", instance "{3f344413-46c2-4419-b46b-85896f241d60}", action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe" with return code 0.

如果我更改 Windows 任务定义以使用双引号而不是单引号,我会得到不同的结果。

编辑的 Windows 任务定义

C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -NoProfile -ExecutionPolicy ByPass -Command ". C:\myscript.ps1; exit $LastExitCode"

新结果

Task Scheduler successfully completed task "\My task", instance "{c44082a8-56fe-4615-aad0-70dca8b71881}", action "C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe" with return code 2147942401.

我怎样才能得到1作为我的任务的返回码? 我是否需要通过某种转换器运行2147942401以获得1 还是这里有其他事情在起作用?

谢谢。

get-scheduledtaskinfo 使用powershell c:\script.ps1为我工作(-command 是默认值):

set-content c:\script.ps1 'exit 1' # or 'exit $error.count'
$action = New-ScheduledTaskAction powershell c:\script.ps1
Register-ScheduledTask script.ps1 \ $action -force # overwrite
start-scheduledtask script.ps1
while ((Get-ScheduledTask script.ps1).State -ne 'Ready') {
  Write-Verbose -Message 'Waiting on scheduled task...'; sleep 1 }

get-scheduledtaskinfo script.ps1

LastRunTime        : 10/23/2022 10:29:29 AM
LastTaskResult     : 1
NextRunTime        :
NumberOfMissedRuns : 0
TaskName           : script.ps1
TaskPath           :
PSComputerName     :

一些疯狂的位数学从 @mklement0 的评论中获取任务调度程序的退出代码在这里: 如何让任务调度程序从 powershell 脚本中检测失败的错误代码

function get-taskschedexitcode ($tasknum) {$tasknum -band -bnot 0x80070000}
get-taskschedexitcode 2147942401

1


1 -bor 0x80070000L

2147942401

要么

2147942401 | % tostring x  # convert to hex

80070001


0x80070001 - 0x80070000  # get exit code

1


2147942401 - 2147942400

1


-join '2147942401'[-2..-1]

01

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM