3

I am using PowerShell to run a script that executes wget to fetch a web page (a simple database import script) and analyzes its output (Error message or "OK").

I am using code from the answer to this previous question of mine.

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

When the result of the wget operation is a 404 - and wget probably returns an errorlevel 1 or 127 - I get the following error message from PowerShell:

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

this obviously refers to my calling the CompareTo() function.

However, wget gets executed and outputs something.

I am suspecting that wget outputs to the error console in this case, and this does not get caught by my $a operation.

How can I redirect the error output so that it gets caught by my script?

Boy, I'm sure going to be question king in the PowerShell tag this month! :)

2
  • 1
    Short question aside: If you're using PowerShell anyway, why even bother with wget? $wc = New-Object Net.WebClient; $rc = ($wc.DownloadString("http://www.example.com/import_db")).CompareTo("OK") Commented Jan 11, 2010 at 19:37
  • I looked into the WebClient documentation on the hint you gave me in my last question, and shied away from the complexity, hoping for a kind soul who would give me an example to start with. Thanks a lot, this I can work with! :) Commented Jan 11, 2010 at 19:50

1 Answer 1

4

To start with

# 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
$?

As for reading the STDERR, i guess the quickest way will be to run the script with stream redirection

$a = c:\path_to_wget\wget.exe --quiet -O - "http://www.example.com/import_db" 2>&1
Sign up to request clarification or add additional context in comments.

2 Comments

If 2>&1 works in this context, I think I'm all right already. Thanks very much!
I would avoid using $? with console apps. I've seen too many that don't honor the convention of 0 == success. Check out the CheckLastExitCode function in this post (I use it in a lot build scripts): keithhill.spaces.live.com/Blog/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.