当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 周五乐趣发送彩色消息

作者:精品下载站 日期:2024-12-14 07:42:14 浏览:15 分类:玩电脑

周五乐趣发送彩色消息


下周是 Pluralsight 成立 10 周年纪念日。为了准备这个喜事,我想送上一份特别的问候。当然,因为我的课程是在 PowerShell 上进行的,所以似乎只适合使用 PowerShell 来显示我的消息。事实上,让我们直接跳到结果。

[玩转系统] 周五乐趣发送彩色消息

我是这样做的。


#requires -version 3.0

#get possible colors but exclude whatever is being used for the current background
$colors = [enum]::GetNames([consolecolor]) | where {$_ -ne $host.ui.RawUI.BackgroundColor}

#the message to be displayed
$msg=@"
************************************
*                                  *
*   Happy Birthday, Pluralsight!   *
*                                  *
************************************
"@

#write each character individually
$msg.ToCharArray() | 
foreach -begin {
Clear-Host
#define a hashtable of parameters to splat to Write-Host
$paramHash=@{NoNewLine=$True;}
} -process { 
   #use a color if not a space
if ($_ -notmatch "\s") {
    $paramhash.ForegroundColor = (Get-Random $colors)
    $paramhash.BackgroundColor = do {
     #get a background color that is different than the 
     #foregroundcolor
     Get-Random $colors
     } until($_ -ne $paramhash.ForegroundColor)   
 } #if not whitespace
 else {
    #clear colors
    $paramhash.Remove("ForegroundColor")
    $paramhash.Remove("BackgroundColor")
 }
  #write each character to the host
  $_ | Write-Host @paramhash

} -end {"`n"}

#no puppies were harmed in the making of this script

该脚本采用一个字符串(在本例中为存储为 $msg 的此处字符串),并使用 Write-Host 将每个字符写入控制台。我使用 Write-Host,这样我就可以利用前景色和背景色。我从可能的控制台颜色列表中为每个颜色获取随机颜色,跳过当前控制台背景使用的颜色。我的脚本使用 Do 循环来获取与前景选择的颜色不同的随机背景颜色。我仅在存在非空格字符时才使用配色方案。我想我可以扭转局面并用 -match 与 \S 进行测试。

无论如何,这是一个简短的脚本,可以以丰富多彩的方式传达信息。享受并度过一个愉快的周末。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯