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

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

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

星期五与 PowerShell 和 ANSI 的乐趣


自从 PowerShell 7 出现以来,我一直在探索如何使用 ANSI 颜色转义序列,这给我带来了很多乐趣。实际上,即使在 Windows PowerShell 中您也可以使用它们。尽管您需要使用不同的转义字符。运行 Get-PSReadlineOption 来看看我在说什么。

今天我有两个快速“玩具”供你玩。第一个是了解如何创建 256 种配色方案的方法。我从 https://en.wikipedia.org/wiki/ANSI_escape_code 提取数据。基本上,您可以使用 [38;5;Nm[0m 的形式定义转义序列。对于 Windows PowerShell,<esc> 值为 $ ([char]0x1b)。您可以在 PowerShell 7 中使用相同的方法或更简单的 `e。 38 表示您想要为前景着色。使用48设置背景。 N 是 1 到 255 之间的值。

这是一个简短的脚本,您可以运行它来查看配色方案。

Param ([switch]$Background)

if ($host.name -match "ISE") {
    return "This script won't work properly in the PowerShell ISE. Run it in a PowerShell console."
}

if ($Background) {
    $X = 48
}
else {
    $X = 38
}

if ($iscoreclr) {
    $esc = "`e"
    $escText = '`e'
}
else {
    $esc = $([char]0x1b)
    $escText = '$([char]0x1b)'
}

Clear-Host

1..255| ForEach-Object {
    $text = "{0}[$X;5;{1}m'Sample Text'{0}[0m" -f $escText,$_

    "{0}`t{1}" -f $text,("$esc[$X;5;$($_)m$('Sample Text')$esc[0m")
}

这是在 Windows PowerShell 中运行的示例。

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

这是背景示例。

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

您可能希望使用这些值之一来通过 Set-PSReadlneOption 更新颜色选项。

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

我的另一个乐趣是创建颜色渐变条。

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

这是一个您可以使用的简单函数。

Function New-ANSIBar {
    [cmdletbinding()]
    Param(
        [Parameter(Mandatory,HelpMessage= "Enter a range of 256 color values, e.g. (232..255)")]
        [ValidateNotNullOrEmpty()]
        [int[]]$Range,
        [Parameter(HelpMessage = "How many spaces do you want in the bar? This will increase the length of the bar.")]
        [int]$Spacing = 1
    )
    $esc = "$([char]0x1b)"
    $out = @()
    $blank = " "*$spacing
    $out += $range | ForEach-Object {
        "$esc[48;5;$($_)m$($blank)$esc[0m"
    }

    $out += $range | Sort-Object -Descending | ForEach-Object {
        "$esc[48;5;$($_)m$($blank)$esc[0m"
    }
    $out -join ""
}

指定 256 个颜色值的范围或集合,该函数将创建渐变条。如果您想要更长的条形,请增加间距。

[玩转系统] 星期五与 PowerShell 和 ANSI 的乐趣

您可以使用它来为您的 PowerShell 配置文件添加一些美观的内容,或者只是为了避免执行实际工作!

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

取消回复欢迎 发表评论:

关灯