Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检测PowerShell脚本执行时出错_Powershell_Batch File - Fatal编程技术网

检测PowerShell脚本执行时出错

检测PowerShell脚本执行时出错,powershell,batch-file,Powershell,Batch File,我有一个PowerShell脚本: 然后我从bat脚本中调用此脚本: 现在,我想知道在bat脚本中,调用的PowerShell脚本是否在出现错误时停止,并且没有到达脚本的末尾。如何执行?一种方法是在脚本中添加顶级陷阱语句,例如: trap { exit 1; # or whatever error code } powershell -noprofile -noninteractive -file <<your script>> IF ERRORLEVEL 1

我有一个PowerShell脚本:

然后我从bat脚本中调用此脚本:


现在,我想知道在bat脚本中,调用的PowerShell脚本是否在出现错误时停止,并且没有到达脚本的末尾。如何执行?

一种方法是在脚本中添加顶级陷阱语句,例如:

trap {
   exit 1; # or whatever error code
}
powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause
注意:陷阱可能被认为是过时的(尽管我喜欢它的顶级),另一个选择是围绕整个脚本进行尝试

因此,当任何命令带异常退出时,将执行trap语句,脚本退出,错误代码为1。如果不添加此项,Powershell将退出,错误代码为0(在所有Powershell运行正常后,尽管脚本没有运行)

然后,您可以使用以下方法检测bat脚本中的错误代码:

trap {
   exit 1; # or whatever error code
}
powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause
powershell-noprofile-noninteractive-file
如果错误级别1(回显错误)否则(回显正常)
暂停
这将检测任何1或更高的错误代码

您也可以使用
%ERRORLEVEL%
,但要小心,这可能会被作为环境变量重写


注意:如果你在嵌套的运行空间中运行你的脚本,你可以考虑使用<代码> $Hoo.StSuxDeExtIt(1)< /C>以确保根宿主退出。

一种方法是向你的脚本添加一个顶级陷阱语句,比如:

trap {
   exit 1; # or whatever error code
}
powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause
注意:陷阱可能被认为是过时的(尽管我喜欢它的顶级),另一个选择是围绕整个脚本进行尝试

因此,当任何命令带异常退出时,将执行trap语句,脚本退出,错误代码为1。如果不添加此项,Powershell将退出,错误代码为0(在所有Powershell运行正常后,尽管脚本没有运行)

然后,您可以使用以下方法检测bat脚本中的错误代码:

trap {
   exit 1; # or whatever error code
}
powershell -noprofile -noninteractive -file <<your script>>

IF ERRORLEVEL 1 (echo ERROR) ELSE (echo OK)

pause
powershell-noprofile-noninteractive-file
如果错误级别1(回显错误)否则(回显正常)
暂停
这将检测任何1或更高的错误代码

您也可以使用
%ERRORLEVEL%
,但要小心,这可能会被作为环境变量重写


注意:如果您在嵌套的运行空间中运行脚本,您可以考虑使用<代码> $Hoo.StSuxDeExtIt(1)< /C>以确保根宿主也退出。

只需添加到马库斯

给出的答案即可。 我注意到陷阱代码甚至隐藏了实际的错误。在我的情况下,我需要实际发生的错误。只需添加修改后的代码即可完成

 trap 
    { 
        write-error $("Error: " + $_.Exception.Message); 
        exit 1; # or whatever error code 
    } 

更多信息请访问

,这是对马库斯给出的答案的补充

我注意到陷阱代码甚至隐藏了实际的错误。在我的情况下,我需要实际发生的错误。只需添加修改后的代码即可完成

 trap 
    { 
        write-error $("Error: " + $_.Exception.Message); 
        exit 1; # or whatever error code 
    } 

处的详细信息是否设置为
%ERRORLEVEL%
set?使用
是否在PowerShell的末尾返回èn›
以及èn›>0帮助?是否设置了
%ERRORLEVEL%
?在PowerShell末尾使用
返回èn›
是否有èn›>0帮助?