如何在 PowerShell 中写入控制台? [英] How to write to the console in PowerShell?

查看:90
本文介绍了如何在 PowerShell 中写入控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对打印(回显)到控制台的各种方式有些困惑.我已经看到有多种方法可以将输出写入控制台,例如:

I am having a little confusion about the various ways to print (echo) to the console. I have seen that there are multiple ways to write output to the console, such as:

Write-Host "Hello world1"
"Hello World2"
Out-Host -InputObject "Hello World3"

所有三种方式都将打印到控制台.中间的一个在某种程度上更简单,更简洁,更易于使用.我也发现当你写一个函数比如:

All three ways will print to the console. The middle one is somehow simpler and less verbose and easier to use. I also find that when you write a function such as:

function GetValues()
{
    "1"
    "2"
}

它仍然返回管道中的两个字符串:

It still returns two strings in the pipeline:

而且我仍然可以打印出这些值:

And I'm still able to print out the values:

foreach ($s in GetValues)
{
    Write-Host "s: " $s
}

我发现只使用带引号的字符串并不总是出现在自定义主机上,我不得不使用 Write-Host 以获取要在自定义主机上打印的值.

The thing that I have found was that using just the quoted string doesn't always appear on custom hosts, and that I have had to use Write-Host to get values to print on custom hosts.

不知何故,我觉得这很令人困惑."Print something" 应该是 Write-Host 的别名还是意图是什么?

Somehow I find this confusing. Is "Print something" supposed to be an alias to Write-Host or what is the intent?

推荐答案

PowerShell 的默认行为只是转储掉出管道的所有内容,而不会被另一个管道元素拾取或分配给变量(或重定向)进入Out-Host.Out-Host 所做的显然是依赖于主机的.

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

让事情脱离管道不能替代Write-Host,后者的唯一原因是在宿主应用程序中输出文本.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

如果您需要输出,请使用 Write-* cmdlet.如果您想从函数返回值,那么只需将对象转储到那里,无需任何 cmdlet.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

这篇关于如何在 PowerShell 中写入控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆