我有一个叫Exit 1
的脚本。但是,当这个脚本通过Windows运行时,我会得到0
或2147942401
的返回代码,但我从来没有得到预期的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
吗?还是这里还有别的事要做?
谢谢。
发布于 2022-10-23 14:31:44
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 :
一些疯狂的数学运算,从@mclement0的注释中获得任务调度程序的退出代码:How get task scheduler to detect failed error code from powershell script。
function get-taskschedexitcode ($tasknum) {$tasknum -band -bnot 0x80070000}
get-taskschedexitcode 2147942401
1
1 -bor 0x80070000L
2147942401
或
2147942401 | % tostring x # convert to hex
80070001
80070001 - 80070000 # get exit code
1
2147942401 - 2147942400
1
-join '2147942401'[-2..-1]
01
https://stackoverflow.com/questions/74143373
复制相似问题