2010-01-11 57 views
3

我正在使用PowerShell运行执行wget的脚本来获取网页(简单数据库导入脚本)并分析其输出(错误消息或“确定”) 。Powershell脚本:无法读取执行的程序的返回值

我正在使用我的代码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

短的问题放在一边:如果你是无论如何使用PowerShell,为什么还要用'wget'? '$ wc = New-Object Net.WebClient; $ rc =($ wc.DownloadString(“http://www.example.com/import_db”))。CompareTo(“OK”)' – Joey 2010-01-11 19:37:34

+0

我查看了WebClient文档中提供给我最后一个问题的提示,并避开了复杂性,希望有一个善良的灵魂能够给我一个例子来开始。非常感谢,我可以合作! :) – 2010-01-11 19:50:17

回答

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 
+0

如果'2>&1'在这种情况下工作,我想我已经好了。非常感谢! – 2010-01-11 19:10:19

+0

ü欢迎................. 15c – Amirshk 2010-01-11 19:41:45

+0

我会避免使用$?控制台应用程序。我见过太多不遵守0 ==成功的约定。查看这篇文章中的CheckLastExitCode函数(我在很多构建脚本中使用它):http://keithhill.spaces.live.com/Blog/cns!5A8D2641E0963A97!7107.entry?wa=wsignin1.0&sa=36637920 – 2010-01-11 21:04:43