How to suppress output and check whether or not a command is successful?

五迷三道 提交于 2019-12-06 13:34:39

Use $LASTEXITCODE -eq 0 rather than $? to reliably detect a nonzero exit code (typically signaling failure) reported by an external program.

You can then use *> $null to categorically suppress all output without having to worry about the impact of that redirection on $?:

mysql -u root --password=mypass -e "show databases" *>$null
if ($LASTEXITCODE -eq 0) {
  "Hooray!"
} else {
  "Boo!"
}

Using a redirection that involves PowerShell's error stream - either explicitly via 2> or implicitly via *> - means that if any data is received via that stream - which in the case of calling an external program means output from stderr - PowerShell sets $? to $false.

However, in the realm of external console / terminal programs, stderr isn't just used to output error information, but any information that isn't data, such as status information. Therefore, you cannot infer failure from the presence of stderr output.

External console / terminal programs communicate their success status solely via their exit code, which PowerShell reflects in the automatic $LASTEXITCODE variable.

It follows from the above that $? can be $false even if the exit code is 0, so it isn't a reliable success indicator - unlike $LASTEXTICODE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!