views:

316

answers:

3

I am running a PowerShell script from within a batch file. The script fetches a web page and checks whether the page's content is the string "OK".

The PowerShell script returns an error level to the batch script.

The batch script is executed by ScriptFTP, an FTP automation program. If an error occurs, I can have ScriptFTP send the full console output to the administrator via E-Mail.

In the PowerShell script, I would like to output the return value from the web site if it is not "OK", so the error message gets included in the console output, and thus in the status mail.

I am new to PowerShell and not sure which output function to use for this. I can see three:

  • Write-Host
  • Write-Output
  • Write-Error

What would be the right thing to use to write to the Windows equivalent of stdout?

+1  A: 

You can use any of these in your scenario since they write to the default streams (output and error). If you were piping output to another commandlet you would want to use Write-Output, which will eventually terminate in Write-Host.

This article describes the different output options: Powershell O is for Output

GrayWizardx
Thanks for the link. Goodness, this is *complicated*. If Write-host is some sort of endpoint or flushing function, I will try and go with that and report back.
Pekka
+2  A: 

I think in this case you will need write-output.

If you have a script like

write-output "test1";
write-host "test2";
"test3";

then, if you call the script with redirected output, something like yourscript.ps1 > out.txt, you will get test2 on the screen test1\ntest3 in the "out.txt".

If a batch file runs a PowerShell command, it will most likely capture the "write-output" command. I have had "long discussions" with system administrators about what should be written to the console and what should not. We have now agreed that only information if the script executed successfully or died has to be write-host'ed, and everything that is the script's author might need to know about the execution (what items were updated, what fields were set et cetera) goes to write-output. This way, when you submit a script to the admin, he can easily runthescript.ps1 >someredirectedoutput.txt and see on the screen, if everything is ok. Then send the "someredirectedoutput.txt" back to the developers.

naivists
+1  A: 

Simply outputting something is PowerShell is a thing of beauty - and one its greatest strengths. For example, the common Hello, World! application is reduced to a single line:

"Hello, World!"

It creates a string object, assigns the aforementioned value, and being the last item on the command pipeline it calls the .toString() method and outputs the result to STDOUT (by default). A thing of beauty.

The other Write-* commands are specific to outputting the text to their associated streams, and have their place as such.

Goyuix
Ooh, it's that easy! Thanks very much!
Pekka