首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Windows任务计划程序不从Powershell脚本返回$LASTEXITCODE

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

Stack Overflow用户
提问于 2022-10-20 16:33:40
回答 1查看 60关注 0票数 0

我有一个叫Exit 1的脚本。但是,当这个脚本通过Windows运行时,我会得到02147942401的返回代码,但我从来没有得到预期的1。详情如下。

脚本内容

代码语言:javascript
运行
复制
Exit 1

Windows任务定义:

代码语言:javascript
运行
复制
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任务定义

代码语言:javascript
运行
复制
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吗?还是这里还有别的事要做?

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2022-10-23 14:31:44

get-scheduledtaskinfo在powershell c:\script.ps1中为我工作(-command是默认的):

代码语言:javascript
运行
复制
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     :

一些疯狂的数学运算,从@mclement0的注释中获得任务调度程序的退出代码:How get task scheduler to detect failed error code from powershell script

代码语言:javascript
运行
复制
function get-taskschedexitcode ($tasknum) {$tasknum -band -bnot 0x80070000}
get-taskschedexitcode 2147942401

1


1 -bor 0x80070000L

2147942401

代码语言:javascript
运行
复制
2147942401 | % tostring x  # convert to hex

80070001


80070001 - 80070000  # get exit code

1


2147942401 - 2147942400

1


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

01
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74143373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档