You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell自定义Draw-Line函数未指定参数时设置默认值咨询

解决方法

PowerShell 中为单个函数参数设置默认值不需要写在[Parameter()]特性内,直接在参数类型声明后赋值即可,你之前的写法属于语法错误。

1. 修正参数声明块

将可选参数的默认值直接赋值在变量后方,同时建议将$ConsoleWidth改为int类型,更适配长度计算逻辑:

function Draw-Line{
    param (
        [Parameter(Mandatory = $true)] [int] $ConsoleWidth,
        [Parameter(Mandatory = $false)] [string] $Position = "middle",
        [Parameter(Mandatory = $false)] [string] $LeftContent = "none",
        [Parameter(Mandatory = $false)] [string] $RightContent = "none"
    )

2. 补全空内容判断逻辑

你已经实现了左侧内容为空的处理,补充右侧内容为空的逻辑即可,避免多余的装饰符参与长度计算:

$Bar = "─"
    # 你可以给颜色变量加默认值,避免运行时报错
    $LineColor = "Gray"
    $TitleColor = "Cyan"

    # 处理位置逻辑
    if ( $Position -eq "top" ){
        $BeforeLeft = "┌──┤ "
    } elseif ( $Position -eq "bottom" ){
        $BeforeLeft = "└──┤ "
    } else {
        $BeforeLeft = "───┤ "
    }
    $AfterLeft = " ├"

    # 处理左侧内容为空的情况
    if ( $LeftContent -eq "none" ){
        $LeftContent,$BeforeLeft,$AfterLeft = "","",""
    }

    $BeforeRight = "┤ "
    $AfterRight = " ├──"
    # 处理右侧内容为空的情况
    if ( $RightContent -eq "none" ){
        $RightContent,$BeforeRight,$AfterRight = "","",""
    }

    # 长度计算逻辑保持不变即可
    $LeftTotal = $BeforeLeft + $AfterLeft + $LeftContent
    $RightTotal = $BeforeRight + $RightContent + $AfterRight 
    $Difference = $ConsoleWidth - ( $LeftTotal.Length + $RightTotal.Length )
    $Line = $Bar * $Difference

    # 保留你的调试线和绘制逻辑即可
    Write-Host "<........|.........|.........|.........|.........|.........|.........|.........>" #Debug line for confirming widths, 80 columns wide.

    #Draw the line:    
    Write-Host $BeforeLeft -ForegroundColor $LineColor -NoNewline
    Write-Host $LeftContent -ForegroundColor $TitleColor -NoNewline
    Write-Host $AfterLeft -ForegroundColor $LineColor -NoNewline 
    Write-Host $Line -ForegroundColor $LineColor -NoNewline
    Write-Host $BeforeRight -ForegroundColor $LineColor -NoNewline
    Write-Host $RightContent -ForegroundColor $LineColor -NoNewline 
    Write-Host $AfterRight -ForegroundColor $LineColor
}

调用示例

当你不传入-RightContent参数时,会自动按none逻辑处理,右侧完全用横线填充:

Draw-Line -ConsoleWidth 80 -Position top -LeftContent "Window Title"

输出效果:

┌──┤ Window Title ├──────────────────────────────────────────────────────────────

内容的提问来源于stack exchange,提问作者Stuart Wood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:00:04