windows 如何在 PowerShell 中输出内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2038181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:02:10  来源:igfitidea点击:

How to output something in PowerShell

windowspowershell

提问by Pekka

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".

我正在从批处理文件中运行 PowerShell 脚本。该脚本获取一个网页并检查该页面的内容是否为字符串“OK”。

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

PowerShell 脚本向批处理脚本返回错误级别。

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.

批处理脚本由ScriptFTP执行,是一个 FTP 自动化程序。如果发生错误,我可以让 ScriptFTP 通过电子邮件将完整的控制台输出发送给管理员。

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.

在 PowerShell 脚本中,如果不是“OK”,我想从网站输出返回值,因此错误消息包含在控制台输出中,从而包含在状态邮件中。

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

我是 PowerShell 的新手,不确定要使用哪个输出函数。我可以看到三个:

  • Write-Host
  • Write-Output
  • Write-Error
  • 写主机
  • 写输出
  • 写错误

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

什么是写入 Windows 等价物的正确方法stdout

采纳答案by Goyuix

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:

简单地输出一些东西是 PowerShell 是一件美丽的事情 - 也是它最大的优势。例如,常见的 Hello, World! 应用程序减少到一行:

"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.

它创建一个字符串对象,分配上述值,并作为命令管道上的最后一项,它调用该.toString()方法并将结果输出到STDOUT(默认情况下)。美的东西。

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

其他Write-*命令特定于将文本输出到其关联的流,并具有它们的位置。

回答by naivists

I think in this case you will need Write-Output.

我认为在这种情况下您将需要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 test2on the screen test1\ntest3\nin the "out.txt".

然后,如果您使用重定向输出调用脚本,例如yourscript.ps1 > out.txt,您将在“out.txt”中test2进入屏幕test1\ntest3\n

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 -nis impossible in PowerShell with the native commands). If you want (the somewhat basic and easy in Bash) functionality of echo -nthen see samthebest's answer.

请注意,“test3”和 Write-Output 行将始终在您的文本中附加一个新行,并且 PowerShell 无法阻止它(也就是说,echo -n在 PowerShell 中使用本机命令是不可能的)。如果你想要(在Bash 中有点基本和简单)的功能,echo -n那么请参阅samthebest's answer

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.txtand see on the screen, if everything is OK. Then send the "someredirectedoutput.txt" back to the developers.

如果批处理文件运行 PowerShell 命令,它很可能会捕获 Write-Output 命令。我与系统管理员就什么应该写入控制台以及什么不应该进行了“长时间的讨论”。我们现在已经同意,脚本成功执行或死亡的唯一信息必须被Write-Host修改,脚本作者可能需要知道的关于执行的所有信息(更新了哪些项目,设置了哪些字段等)写入输出。这样,当您向系统管理员提交脚本时,他可以轻松runthescript.ps1 >someredirectedoutput.txt查看屏幕上是否一切正常。然后将“someredirectedoutput.txt”发送回开发人员。

回答by user2426679

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

我认为以下是 Echo 与Write-Host 的一个很好的展示。注意 test() 实际上是如何返回一个整数数组,而不是一个很容易让人相信的整数。

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

回答by GrayWizardx

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.

您可以在您的场景中使用其中任何一个,因为它们写入默认流(输出和错误)。如果您将输出通过管道传输到另一个命令行开关,您会想要使用Write-Output,它最终将在Write-Host 中终止。

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

本文介绍了不同的输出选项:PowerShell O 用于输出

回答by jordan

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.

Magenta 可以是“System.ConsoleColor”枚举值之一 - Black、DarkBlue、DarkGreen、DarkCyan、DarkRed、DarkMagenta、DarkYellow、Gray、DarkGray、Blue、Green、Cyan、Red、Magenta、Yellow、White。

The + $File.FullNameis optional, and shows how to put a variable into the string.

+ $File.FullName是可选的,并展示了如何把一个变量到字符串。

回答by samthebest

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

您根本无法让 PowerShell 忽略那些讨厌的换行符。没有执行此操作的脚本或 cmdlet。

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

当然,Write-Host 绝对是无稽之谈,因为您无法从它重定向/管道!你只需要自己写:

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:\>

回答by mklement0

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

什么是写入 Windows 等效标准输出的正确方法?

In effect, but very unfortunately, both Windows PowerShell and PowerShell Core as of v7.0, send allof their 6(!) output streamsto stdoutwhen called from the outside, via PowerShell's CLI.

效果,但是很不幸的是,无论是Windows PowerShell和PowerShell核心为V7.0,送所有的6(!)的输出流标准输出时,称为从外面,通过PowerShell的CLI

  • See this GitHub issuefor a discussion of this problematic behavior, which likely won't get fixed for the sake of backward compatibility.

  • In practice, this means that whatever PowerShell stream you send output towill be seen as stdoutoutput by an external caller:

    • E.g., if you run the following from cmd.exe, you'll see nooutput, because the stdout redirection to NULapplies equally to all PowerShell streams:

      • C:\>powershell -noprofile -command "Write-Error error!" >NUL
    • However - curiously - if you redirect stderr, PowerShell doessend its error stream to stderr, so that with 2>you cancapture 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
  • 有关问题行为的讨论,请参阅此 GitHub 问题,出于向后兼容性的考虑,该问题可能不会得到修复。

  • 实际上,这意味着您将输出发送到的任何 PowerShell 流都将被外部调用者视为stdout输出:

    • 例如,如果您从 运行以下命令cmd.exe,您将看不到任何输出,因为 stdout 重定向NUL同样适用于所有 PowerShell 流:

      • C:\>powershell -noprofile -command "Write-Error error!" >NUL
    • 但是 - 奇怪的是 -如果您重定向 stderr,PowerShell确实将其错误流发送到 stderr,以便2>可以有选择地捕获错误流输出;以下输出只是'hi'- 成功流输出 - 同时捕获文件中的错误流输出err.txt

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

The desirablebehavioris:

理想的行为是:

  • Send PowerShell's success output stream(number 1) to stdout.
  • Send output from all other streamsto stderr, which is the only option, given that betweenprocesses only 2output streams exist - stdout (standard output) for data, and stderr (standard error) for error messages andall 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.

  • 将 PowerShell 的成功输出流(数字1)发送到stdout
  • 从发送输出所有其他流stderr的给定的,这是唯一的选择,那之间仅处理2输出流存在-标准输出(标准输出)用于数据,和stderr(标准误差)的错误消息所有其它类型的消息-例如作为状态信息 - 这不是data

  • 建议在您的代码中进行这种区分,即使它目前没有受到尊重



InsidePowerShell:

PowerShell 中

  • Write-Hostis for displayoutput, and bypassesthe 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-Hostto the newly introduced information stream(number 6), so since then it ispossible to capture and redirect Write-Hostoutput.

  • Write-Erroris meant for writing non-terminatingerrors to the error stream(number 2); conceptually, the error stream is the equivalent of stderr.

  • Write-Outputwrites 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-Outputis rarely neededdue to PowerShell's implicit outputfeature:
      • Output from any command or expression that isn't explicitly captured, suppressed or redirected is automaticallysent 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.
  • Write-Host用于显示输出,并绕过成功输出流-如这样,其输出既不能(直接地)捕获在一个变量也不抑制也不重定向。

    • 它的初衷只是创建用户反馈并创建简单的、基于控制台的用户界面(彩色输出)。

    • 由于被捕获或重定向现有无力,制成的PowerShell版本5Write-Host到新引入的信息流(数6),这样以来则能够捕获和重定向Write-Host输出。

  • Write-Error用于非终止错误写入错误流(数字2);从概念上讲,错误流相当于 stderr。

  • Write-Output写入成功 [output] 流(number 1),这在概念上等同于 stdout;它是数据(结果)写入的流。

    • 但是,由于 PowerShell 的隐式输出功能,很少需要显式使用Write-Output
      • 任何未明确捕获、抑制或重定向的命令或表达式的输出都会自动发送到成功流;例如,Write-Output "Honey, I'm $HOME""Honey, I'm $HOME"是等价的,后者不仅更简洁,而且速度更快。