如何使用Box字符在Powershell中创建一个框

时间:2014-04-04 21:36:29

标签: powershell

我想知道如何在PowerShell中创建一个文本菜单框。

我应该是框字符来执行此操作并将这些字符的值放入数组中。

$ BoxCharacters =" =","╔","╗","╚"," ╝","║"

但是我如何将它们乘以我所需的菜单所需的数字。例如,$ Var.length等于6,我想将其乘以。

我还想知道如何将此数字相乘以添加空格,例如$ Var.length *" "这将插入,如果长度为6,则插入6个空格。但这是错误的,所以我该怎么做呢。

任何帮助都会很棒,谢谢!

2 个答案:

答案 0 :(得分:1)

我会提供类似的东西,但有点多才多艺,因为你可以在菜单中添加标题。它将为您输入数字,并为我提供更好的缓冲区。

Function MenuMaker{
    param(
        [string]$Title = $null,
        [parameter(Mandatory=$true,
        ValueFromPipeline = $true)][String[]]$Selections
        )

    $Width = if($Title){$Length = $Title.Length;$Length2 = $Selections|%{$_.length}|Sort -Descending|Select -First 1;$Length2,$Length|Sort -Descending|Select -First 1}else{$Selections|%{$_.length}|Sort -Descending|Select -First 1}
    $Buffer = if(($Width*1.5) -gt 78){(78-$width)/2}else{$width/4}
    if($Buffer -gt 6){$Buffer = 6}
    $MaxWidth = $Buffer*2+$Width+$($Selections.count).length
    $Menu = @()
    $Menu += "╔"+"═"*$maxwidth+"╗"
    if($Title){
        $Menu += "║"+" "*[Math]::Floor(($maxwidth-$title.Length)/2)+$Title+" "*[Math]::Ceiling(($maxwidth-$title.Length)/2)+"║"
        $Menu += "╟"+"─"*$maxwidth+"╢"
    }
    For($i=1;$i -le $Selections.count;$i++){
        $Item = "$i`. "
        $Menu += "║"+" "*$Buffer+$Item+$Selections[$i-1]+" "*($MaxWidth-$Buffer-$Item.Length-$Selections[$i-1].Length)+"║"
    }
    $Menu += "╚"+"═"*$maxwidth+"╝"
    $menu
}

因此,如果输入MenuMaker -Title "Test Menu" -Selections @("Dog","Horse","Squirrel"),则输出:

╔══════════════╗
║  Test Menu   ║
╟──────────────╢
║  1. Dog      ║
║  2. Horse    ║
║  3. Squirrel ║
╚══════════════╝

答案 1 :(得分:0)

假设您的菜单是由回车符新行(`r`n)包围的文本块,以下代码将在文本块周围写一个框:

$HorizontalBoxChar = [string][char]9552
$VerticalBoxChar = [string][char]9553
$TopLeftBoxChar = [string][char]9556
$TopRightBoxChar = [string][char]9559
$BottomLeftBoxChar = [string][char]9562
$BottomRightBoxChar = [string][char]9565

Function CreateBoxText() {
    Begin {
        $lines = @()
    }
    Process {
        $maxLength = 0
        $lineCount = 0
        $_ -split "`r`n" | ForEach-Object {
            $lines += $_
            If ($lines[$lineCount].Length -gt $maxLength) {
                $maxLength = $lines[$lineCount].Length
            }
            $lineCount++
        }
    }
    End {
        $TopLeftBoxChar + ($HorizontalBoxChar * ($maxLength + 2)) + $TopRightBoxChar
        For ($i = 0; $i -lt $lineCount; $i++) {
            $VerticalBoxChar + " " + $lines[$i] + (" " * ($maxLength - $lines[$i].Length + 1)) + $VerticalBoxChar
        }
        $BottomLeftBoxChar + ($HorizontalBoxChar * ($maxLength + 2)) + $BottomRightBoxChar
    }   
}

"List Item 1`r`nList Item 2222`r`nThe Final List Item" | CreateBoxText