Powershell将变量中的主机输出参数写为字符串

use*_*814 1 powershell

$mycolorparams = "-foregroundcolor red -backgroundcolor black"

write-host "I want this foreground in Red and background in black" $mycolorparams
Run Code Online (Sandbox Code Playgroud)

大家好,

这让我抓狂。当我使用 write-host 时,cmdlet 将所有内容返回为字符串:

“我希望前景为红色,背景为黑色 -前景色红色 -背景色黑色”。

不是具有红色文本和黑色背景的实际字符串。

最糟糕的是,这对我来说一直有效,直到我更改了代码中的 var 名称。我不知道从那以后发生了什么改变。我怀疑这与引号有关,因为单引号吐出字符串,双引号读取变量。但是在 text 和 var 上尝试了大量的 single 和 double 变化之后,结果是相同的,只是字符串输出。

在过去的一个小时里,我一直在网上搜寻,但没有运气,有很多例子,但我找不到具体问题的答案。任何帮助表示赞赏,谢谢。

Dun*_*can 5

使用参数展开(尽管我认为它不在旧版本中,因此您可能需要升级到 Powershell 版本 3 或更高版本)。

PS C:\> $opts = @{ForegroundColor="red"; BackgroundColor="black"; object="Hello world"}
PS C:\> write-host @opts
Hello world
Run Code Online (Sandbox Code Playgroud)

或者:

PS C:\> $opts = @{ForegroundColor="red"; BackgroundColor="black"}
PS C:\> write-host @opts -object "Hello world"
Hello world
Run Code Online (Sandbox Code Playgroud)

您需要将选项字符串转换为哈希表或数组。事实上,如果您运行,help about_Splatting您会发现其中一个示例完全涵盖了您的问题:

此示例演示如何在不同命令中重复使用splatted 值。本示例中的命令使用 Write-Host cmdlet 将消息写入主机程序控制台。它使用泼溅来指定前景色和背景色。

To change the colors of all commands, just change the value of the $Colors
variable.

The first command creates a hash table of parameter names and values and 
stores the hash table in the $Colors variable.

           $Colors = @{ForegroundColor = "black"
                       BackgroundColor = "white"}

The second and third commands use the $Colors variable for splatting in a
Write-Host command. To use the $Colors variable, replace the dollar sign 
($Colors) with an At symbol (@Colors).

           # Write a message with the colors in $Colors
           Write-Host "This is a test." @Colors

           # Write second message with same colors. 
           # The position of splatted hash table does not matter.
           Write-Host @Colors "This is another test."
Run Code Online (Sandbox Code Playgroud)