有没有办法在PowerShell

时间:2018-02-05 11:09:38

标签: powershell

我们如何在PowerShell中居中文本? WindowWidth显然不存在,所以是否有办法让文字居中?

我们想要这个输出:

    *
   ***
  *****
 *******

所以我写了

for ($i=1; $i -le 7; $i+=2)
{
  write-host("*" * $i)
}

但我们得到了

*
***
*****
*******

3 个答案:

答案 0 :(得分:2)

您可以计算需要添加的空格,然后按如下方式包含它们:

$Width = 3

for ($i=1; $i -le 7; $i+=2)
{   
    Write-Host (' ' * ($width - [math]::floor($i / 2))) ('*' * $i)
}

答案 1 :(得分:1)

ORA-01489

答案 2 :(得分:0)

我玩得很开心,并以此为基础编写了一些代码,使之成为一个盒子并将文本居中。 我确定有人可以制作一个更干净的版本,但这可以很好地完成工作:)

<span class=class_7>

这给出了这样的输出:

# ----------------------------------------------------------------------------------
#
# Script functions
#
# ----------------------------------------------------------------------------------
function MakeTopAndButtom
{
    $string = "# "
    for($i = 0; $i -lt $Host.UI.RawUI.BufferSize.Width - 4; $i++)
    {
        $string = $string + "-"
    }
    $string = $string + " #"

    return $string
}

function MakeSpaces
{
    $string = "# "
    for($i = 0; $i -lt $Host.UI.RawUI.BufferSize.Width - 4; $i++)
    {
        $string = $string + " "
    }
    $string = $string + " #"
    return $string
}

function CenterText
{
    param($Message)

    $string = "# "

    for($i = 0; $i -lt (([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Max(0, $Message.Length / 2))) - 4; $i++)
    {
        $string = $string + " "
    }

    $string = $string + $Message

    for($i = 0; $i -lt ($Host.UI.RawUI.BufferSize.Width - ((([Math]::Max(0, $Host.UI.RawUI.BufferSize.Width / 2) - [Math]::Max(0, $Message.Length / 2))) - 2 + $Message.Length)) - 2; $i++)
    {
        $string = $string + " "
    }

    $string = $string + " #"
    return $string

}

function LinesOfCodeInCorrentFolder
{
    return (gci -include *.ps1 -recurse | select-string .).Count
}

$MakeTopAndButtom = MakeTopAndButtom
$MakeSpaces = MakeSpaces
$lines = LinesOfCodeInCorrentFolder



# ----------------------------------------------------------------------------------
#
# Run
#
# ----------------------------------------------------------------------------------
$MakeTopAndButtom
$MakeSpaces
$MakeSpaces
$MakeSpaces
$MakeSpaces

CenterText "Lines of .ps1 code in this folder: $($lines)"
CenterText "Press any key to exit"

$MakeSpaces
$MakeSpaces
$MakeSpaces
$MakeSpaces
$MakeTopAndButtom

Read-Host
相关问题