如何在第一个错误时停止 PowerShell 脚本? [英] How to stop a PowerShell script on the first error?

查看:42
本文介绍了如何在第一个错误时停止 PowerShell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 PowerShell 脚本在我运行的任何命令失败时停止(例如 bash 中的 set -e).我同时使用 Powershell 命令(New-Object System.Net.WebClient)和程序(.\setup.exe).

I want my PowerShell script to stop when any of the commands I run fail (like set -e in bash). I'm using both Powershell commands (New-Object System.Net.WebClient) and programs (.\setup.exe).

推荐答案

$ErrorActionPreference = "Stop" 将帮助您解决问题(即这对 cmdlet 非常有用).

$ErrorActionPreference = "Stop" will get you part of the way there (i.e. this works great for cmdlets).

但是对于 EXE,您需要在每次 exe 调用后自己检查 $LastExitCode 并确定是否失败.不幸的是,我不认为 PowerShell 可以提供帮助,因为在 Windows 上,EXE 在构成成功"或失败"退出代码的内容方面并不是非常一致.大多数遵循 0 表示成功的 UNIX 标准,但并非所有人都这样做.查看此博客中的 CheckLastExitCode 函数发布.您可能会发现它很有用.

However for EXEs you're going to need to check $LastExitCode yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.

这篇关于如何在第一个错误时停止 PowerShell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆