Search code examples
powershellalignmenttitle

Automatically Align and Fill with a Char, on Text in Powershell


According to the text length in the variable, I can fill it with a character that I specify for the top and bottom lines.

Sample Variables

$mychar = "#"
$var1 = "Hello"
$var2 = "...Long Title..."
$var3 = "Some New Adventure"
$var4 = "Some New Adventure EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED"

Expecting Output

##########################################################################
########################### Some New Adventure ###########################

##########################################################################
############################ ...Long Title... ############################

##########################################################################???????
##################################### Hello #####################################

##########################################################################???????????????????????????????????????????????????????????????????????????????????
##################################### Some New Adventure EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED EXCEED #####################################

NOTICE: The characters on the right and left of the text should be distributed in the same number.


Solution

  • Seems like this function might accomplish what you're after:

    function dostuff {
        param(
            [Parameter(Mandatory)]
            [string] $InputString,
            [char] $Char = '#',
            [int] $BarLength = 74 # it seems?
        )
    
        $len = $BarLength / 2 - $InputString.Length / 2
        $Char.ToString() * $BarLength
        ' '.PadLeft([Math]::Floor($len), $Char) + $InputString + ' '.PadRight([Math]::Ceiling($len), $Char)
    }
    
    dostuff 'Hello'
    dostuff '...Long Title...'
    dostuff 'Some New Adventure'