自定义PowerShell Add-Border函数Write-Host黑色输出失效问题
问题分析与解决
问题原因
你的函数里判断颜色参数的逻辑有漏洞:当指定-ForegroundColor Black时,[System.ConsoleColor]::Black对应的枚举值是0,而PowerShell里0会被判定为$false,导致If($ForegroundColor)这个条件不成立,黑色没有被加入到$Colors哈希表中,最终Write-Host没应用黑色,而是用了默认文本颜色。
修复方案
把颜色参数的判断逻辑改成检查参数是否被用户显式指定(通过$PSBoundParameters集合),而非直接判断参数值。
修复后的完整函数代码:
Function Add-Border { <# .Synopsis 为字符串添加文本边框。 .Description 该命令会在单行文本周围创建字符边框,可用于格式化文本报告或优化屏幕信息显示效果。 .Parameter Text 需要添加边框的单行文本。 .Parameter Character 用于绘制边框的字符,必须是单个字符。 .Parameter InsertBlanks 在文本前后插入空行,默认是紧贴文本创建边框。查看示例了解效果。 .Parameter Tab 在结果前插入指定数量的制表符。 .Example PS C:\> add-border "PowerShell 牛!" ****************** * PowerShell 牛! * ****************** .Example PS C:\> add-border "PowerShell 牛!" -tab 1 ****************** * PowerShell 牛! * ****************** .Example PS C:\> add-border "PowerShell 牛!" -character "-" -insertBlanks ------------------ - - - PowerShell 牛! - - - ------------------ #> [CmdletBinding()] Param( [Parameter(Position = 0, Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [string]$Text, [Parameter(Position=1, Mandatory)] [ValidateNotNullOrEmpty()] [validateScript({$_.length -eq 1})] [ValidatePattern("[ -~]")] [string]$Character, [Parameter()] [Switch]$InsertBlanks, [int]$Tab = 0, [Parameter()] [System.ConsoleColor]$ForegroundColor, [Parameter()] [System.ConsoleColor]$BackgroundColor, ) Process { # 获取输入文本长度 $Length = $Text.Length # 生成指定数量的制表符 $tabs = "`t"*$tab # 生成边框线 $line = $Character * ($Length+4) # 处理是否插入空行的情况 if ($insertBlanks) { $body = @" $tabs$character $((" ")*$Length) $character $tabs$Character $text $Character $tabs$character $((" ")*$Length) $character "@ } else { $body = "$tabs$Character $text $Character" } # 拼接最终带边框的内容 $OutBorder = @" $tabs$line $body $tabs$line "@ # 处理颜色输出逻辑 $Colors = @{} # 检查ForegroundColor是否被显式指定 If($PSBoundParameters.ContainsKey('ForegroundColor')){ $Colors["ForegroundColor"] = $ForegroundColor } # 检查BackgroundColor是否被显式指定 If($PSBoundParameters.ContainsKey('BackgroundColor')){ $Colors["BackgroundColor"] = $BackgroundColor } # 无颜色参数时直接输出文本,否则带颜色输出 If($Colors.Count -eq 0){ $OutBorder }else{ Write-Host $OutBorder @Colors } } }
关键修改点
- 把原来的
If($ForegroundColor)和If($BackgroundColor)换成$PSBoundParameters.ContainsKey('参数名'),只要用户显式指定了参数,不管值是什么都会被加入颜色哈希表。 - 最后判断是否用颜色输出的逻辑改成检查
$Colors.Count -eq 0,逻辑更清晰准确。
现在测试Add-Border "测试黑色" -Character "*" -ForegroundColor Black,黑色文本就能正常显示了。
内容的提问来源于stack exchange,提问作者Fitzgery
相关产品推荐
相关产品推荐

