简体   繁体   中英

Powershell script: Can't read return value of executed program

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! :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM