Powershell 写入主机带换行符,而写入输出不带换行符
命令Powershell 写入主机带换行符,而写入输出不带换行符,powershell,Powershell,命令$output=Invoke表达式“cfn lint*.yaml”为$output提供了一个数组: $output.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[]
$output=Invoke表达式“cfn lint*.yaml”
为$output
提供了一个数组:
$output.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
Write Output$Output
为我提供了这个漂亮的输出:
Write-Output $output
W2506 Parameter AMIID should be of type [AWS::EC2::Image::Id,
AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>]
trace3-ec2-virtual-machine-creation.yaml:27:3
W2001 Parameter VpcId not used.
trace3-ec2-virtual-machine-creation.yaml:32:3
为什么要这样做
我知道我可以通过调用
Write Host($output | Out String)
来解决这个问题,但我不明白为什么这样做。Write output
将[-InputObject]
作为参数,而Write Host
将[-Object]]
作为参数
返回作为输入提交的对象
将对象发送到主机。它不返回任何对象。但是,主机将显示写入主机发送给它的对象
如您所见,Write-Output
将PSObject
的数组作为输入参数,并返回与输出相同的数组
Out-String
与Write-Host
配合良好,因为它正在将数组转换为一个多行字符串
,因此Write-Host
会将它作为文本返回到信息流,而没有Out-String
则会将数组的所有行合并为一个字符串行字符串
PS /> $test = @(
'this is a'
'test'
)
$writeHost = Write-Host -Object $test 6>&1
$writeOutput = Write-Output -Object $test
$writeHost.GetType()
$writeOutput.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False InformationRecord System.Object
True True Object[] System.Array
编辑
根据您的评论,我不知道为什么,我无法找到有关cmdlet的MS文档的任何相关信息,但我们可以假设它正在对输入对象进行某种操作。我们知道写主机
是写信息
的包装器
以该函数为例,它接收一个[object]
,在这种情况下,它接收一个数组
,其中有两个项目作为输入,并将其输入的字符串
表示形式写入信息流:
$test = @(
'this is a'
'test'
)
function TestString ([object]$String) {
Write-Information ([string]$String) -InformationAction Continue
}
PS /> TestString $test
this is a test
为什么Write Host会将数组中的所有行都转换成一行字符串?@PortMan我的假设是因为它是如何编码的,但我不能确定。有可能它的编码是为了去掉所有新行
和回车
,并将它们合并到一个单行字符串中。@PortMan我在我的答案中添加了一个编辑,希望有意义。
$test = @(
'this is a'
'test'
)
function TestString ([object]$String) {
Write-Information ([string]$String) -InformationAction Continue
}
PS /> TestString $test
this is a test