Powershell脚本:无法读取已执行程序的返回值

时间:2010-01-11 18:38:44

标签: windows powershell

我使用PowerShell运行执行wget的脚本来获取网页(一个简单的数据库导入脚本)并分析其输出(错误消息或“确定”)。

我正在使用我的this previous question答案中的代码。

$a = c:\path_to_wget\wget.exe --quiet -O - "http://www.example.com/import_db"
$rc = $a.CompareTo("OK")
exit $rc

当wget操作的结果是404时 - 而wget可能返回错误级别1或127 - 我从PowerShell收到以下错误消息:

You cannot call a method on a null-valued expression.

这显然是指我调用CompareTo()函数。

然而, wget被执行并输出一些内容。

我怀疑在这种情况下wget输出到错误控制台,这不会被我的$ a操作捕获。

如何重定向错误输出以使其被我的脚本捕获?

男孩,我肯定会在本月的PowerShell标签中成为问题王! :)

1 个答案:

答案 0 :(得分:4)

开始
# This will hold the last executed EXE return code
$LastExitCode
# For console apps, where 0 is true, else is false, this will hold either True or False
$?

至于阅读STDERR,我想最快的方法是使用流重定向运行脚本

$a = c:\path_to_wget\wget.exe --quiet -O - "http://www.example.com/import_db" 2>&1