windows - 处理外部程序错误

标签 windows powershell error-handling ps1

我正在编写执行外部程序和其他脚本的PowerShell脚本。

我在主脚本中调用.exe和.ps1脚本,如下所示:

& ./directory/file.exe

or

& ./directory/script.ps1

如何捕捉错误?

就像unix一样,我可以使用$?并执行以下操作:
if($? -ne 0) then exit 1 ...

这是最好的方法吗?
我们可以在PowerShell中使用 EXIT 吗?

顺便说一句,使用“&”是调用.exe文件的最佳方法吗? .ps1?

最佳答案

powershell中的$?是 bool(boolean) 值,仅反射(reflect)前一个powershell语句的执行状态。

对于外部程序,请检查$LASTEXITCODE:

& .\directory\file.exe 
if($LASTEXITCODE){
    return 
}

在上面的示例中,我使用return-exit也可以使用,但是我通常避免使用exit,因为它会指示主机应用程序立即退出,如果您想从另一个脚本中调用脚本,则可能会或可能不希望这样做。将来进行较大规模操作的一部分。

调用运算符&将与可执行文件和Powershell脚本文件路径完美配合。

关于windows - 处理外部程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622298/

相关文章:

windows - 在运行时更改进程名称

c++ - 我写 Func1(int &a) 和 Func1(int *a) 有什么区别?

powershell - IIS 高级日志记录 - 通过 Powershell 编写过滤器脚本

python - BeautifulSoup错误AttributeError : 'NoneType' object has no attribute 'getText'

windows - 如何以编程方式确定用户帐户是否是 Windows 中特定组的成员?

html - 使用发送邮件消息发送嵌入式图像

powershell - 如何终止变量扩展以在 Powershell 中创建字符串

c - 直接 C 程序中的错误处理有什么好的习惯用法吗?

.net - 错误记录: Source Error and Source File

windows - 在Windows 10上链接两个Docker容器