Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 305 Vote(s) - 3.66 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to output something in PowerShell

#1
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][1], 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]:

[To see links please register here]

Reply

#2
You simply cannot get PowerShell to ommit those pesky newlines. There is no script or cmdlet that does this.

Of course Write-Host is absolute nonsense because you can't redirect/pipe from it! You simply have to write your own:

using System;

namespace WriteToStdout
{
class Program
{
static void Main(string[] args)
{
if (args != null)
{
Console.Write(string.Join(" ", args));
}
}
}
}

E.g.

PS C:\> writetostdout finally I can write to stdout like echo -n
finally I can write to stdout like echo -nPS C:\>
Reply

#3
I think in this case you will need [Write-Output][1].

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\n` in the "out.txt".

Note that "test3" and the Write-Output line will always append a new line to your text and there is no way in PowerShell to stop this (that is, `echo -n` is impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in [Bash][2]) functionality of `echo -n` then see [samthebest's answer][3].

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 the 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 system administrator, 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.

[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]



Reply

#4
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.
Reply

#5
Write-Host "Found file - " + $File.FullName -ForegroundColor Magenta

Magenta can be one of the "System.ConsoleColor" enumerator values - Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.

The `+ $File.FullName` is optional, and shows how to put a variable into the string.
Reply

#6
I think the following is a good exhibit of Echo vs. [Write-Host][1]. Notice how test() actually returns an array of ints, not a single int as one could easily be led to believe.

function test {
Write-Host 123
echo 456 # AKA 'Write-Output'
return 789
}

$x = test

Write-Host "x of type '$($x.GetType().name)' = $x"

Write-Host "`$x[0] = $($x[0])"
Write-Host "`$x[1] = $($x[1])"

Terminal output of the above:

123
x of type 'Object[]' = 456 789
$x[0] = 456
$x[1] = 789

[1]:

[To see links please register here]


Reply

#7
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][1], which will eventually terminate in [Write-Host][2].

This article describes the different output options: [PowerShell O is for Output][3]

[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

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

**In *effect*, but very *unfortunately***, both **Windows PowerShell and PowerShell Core as of v7.2, send _all_ of their 6(!) [output streams](

[To see links please register here]

) to _stdout_** when **called _from the outside_, via PowerShell's [CLI](

[To see links please register here]

)**.

* See [GitHub issue #7989](

[To see links please register here]

) for a discussion of this problematic behavior, which likely won't get fixed, so as to preserve backward compatibility.

* **In practice, this means that _whatever PowerShell stream you send output to_ will be seen as _stdout_ output by an external caller:**

* E.g., if you run the following from `cmd.exe`, you'll see _no_ output, because the stdout redirection to `NUL` applies equally to all PowerShell streams:

* `C:\>powershell -noprofile -command "Write-Error error!" >NUL`

* However - curiously - **if you _redirect stderr_, PowerShell _does_ send its error stream to stderr**, so that with `2>` you _can_ capture the error-stream output selectively; the following outputs just `'hi'` - the success-stream output - while capturing the error-stream output in file `err.txt`:

* `C:\>powershell -noprofile -command "'hi'; Write-Error error!" 2>err.txt`

The **_desirable_ behavior** is:

* Send PowerShell's **_success output stream_ (number `1`) to _stdout_**.
* Send output from **_all other streams_ to _stderr_**, which is the only option, given that _between_ processes only _2_ output streams exist - stdout (standard output) for _data_, and stderr (standard error) for error messages _and_ all other types of messages - such as status information - that aren't _data_.

* **It's advisable to make this distinction in your code, even though it currently isn't being respected**.

---

**_Inside_ PowerShell**:

* **`Write-Host`** is **for _display_ output**, and **_bypasses_ the success output stream** - as such, its output can neither be (directly) captured in a variable nor suppressed nor redirected.

* Its original intent was simply to create user feedback and create simple, console-based user interfaces (colored output).

* Due to the prior inability to be captured or redirected, PowerShell version 5 made `Write-Host` write to the newly introduced _information stream_ (number `6`), so since then it _is_ possible to capture and redirect `Write-Host` output.

* **`Write-Error`** is meant for **writing _non-terminating_ errors to the _error stream_** (number `2`); conceptually, the error stream is the equivalent of stderr.

* **`Write-Output`** writes to the **_success [output] stream_** (number `1`), which is conceptually equivalent to stdout; it is **the stream to write _data_ (results) to.**
* However, **explicit use of `Write-Output` is rarely needed** due to PowerShell's **_implicit output_ feature**:
* **Output from any command or expression that isn't explicitly captured, suppressed or redirected is _automatically_ sent to the success stream**; e.g., `Write-Output "Honey, I'm $HOME"` and `"Honey, I'm $HOME"` are equivalent, with the latter not only being more concise, but also faster.
* See [this answer](

[To see links please register here]

) for more information.


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through