我正在使用PowerShell 5.1,我想将一些有色文本存储到变量中。我知道您可以使用写入式
将一些彩色字符串打印到控制台中,如下所示:
但是,我似乎无法保存它们进入变量:
我尝试了各种解决方案,例如给出的解决方案此处” ,但似乎没有什么可用。
I'm using PowerShell 5.1, and I want to store some colored text into a variable. I'm aware that you can use Write-Host
to print out some colored strings into the console, as shown below:
However, I can't seem to save them into a variable:
I've tried various solutions such as the ones given here but nothing seems to work.
发布评论
评论(3)
您可以在变量中存储
witr-host
所需的参数参数:@
在变量路径/名称的前面称为 splatting 操作员,您可以在大约_splatting 帮助主题You can store the parameter arguments you need for
Write-Host
in a variable:The
@
in front of the variable path/name is known as the splatting operator, you can read more in theabout_Splatting
help topic试图将文本输出分配到变量的原因,
$ hi = write-host ...
,是因为write> write-host
not return return /em>它打印的文本 - 它将带有ANSI颜色代码的文本发送到控制台。您可以找出一个方便的方案,用于在要打印的文本中包含颜色信息,并编写代码,该代码在将文本打印到屏幕上时使用该颜色信息,如其他已发布的答案所建议。
例如,
这可能很乏味。也许检查 psgallery 查看是否有任何包装包的包装文本可以为您的应用程序提供便利的命令。
The reason the attempt to assign the text output to a variable,
$hi = Write-Host ...
, is becauseWrite-Host
doesn't return the text it prints - it sends the text with ANSI color codes to the console.You could figure out a convenient scheme for including color information in the text you want to print, and write code that uses that color information as it prints the text to the screen, as suggested by the other posted answer.
For instance,
This could be pretty tedious though. Maybe check PSGallery to see if there are any packages dealing with colorized text that provide commands convenient for your application.
使用格式使用PowerShell ANSI逃脱序列:
$([char] 0x1b)[#m
其中
#
代表一个数字。 ANSI逃生序列的更多信息)(请参阅在此处,有关 看起来像这样:
Use PowerShell ANSI escape sequences with the format:
$([char]0x1b)[#m
where
#
represents a number. (see here for more info about ANSI escape sequences)In the case of the question above, it would look like this: