如何在Powershell中的其他字符串中插入多行字符串?

亚历克斯

我有以下powershell-2.0脚本

$FailedTests = Get-ChildItem $PathLog | ?{ $_.PSIsContainer } | select name
"+++"
$FailedTests
"+++"

$Text = "
Summary
----------
$FailedTests
"
$Text
"+++"

生成的输出是:

+++

Name : Test1


Name : Test2

+++

Summary
----------


+++

在我看来,这绝对是不合逻辑的。我期望以下输出:

+++

Name : Test1


Name : Test2

+++

Summary
----------


Name : Test1


Name : Test2

+++

到底是怎么回事?如何解决这个问题?

也许$FailedTests不是字符串?那是什么 如何将其转换为字符串?

Frode F.

$FailedTests不是字符串,而是其他某种对象。您的代码目前是这样的:

$FailedTests = [pscustomobject]@{ Name = "Test1"},[pscustomobject]@{ Name = "Test2"}

#I had to use `Format-List *` to output the sample-objects in the same format as your objects.
#The default format are diferent between different types of objects

"+++"
$FailedTests | Format-List *
"+++"

$Text = "
Summary
----------
$FailedTests
"
$Text
"+++"

输出:

+++


Name : Test1

Name : Test2



+++

Summary
----------


+++

对象ToString()不输出任何东西。最简单的解决方案是| Out-String将控制台中获得的格式转换为字符串。这将需要一个子表达式$()前任:

$FailedTests = [pscustomobject]@{ Name = "Test1"},[pscustomobject]@{ Name = "Test2"}

"+++"
$FailedTests | Format-List *
"+++"

$Text = "
Summary
----------
$($FailedTests | Format-List * | Out-String)
"
$Text
"+++"

输出:

+++


Name : Test1

Name : Test2



+++

Summary
----------


Name : Test1

Name : Test2





+++

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章