Friday Fun: Crossing the Border with PowerShell

Today’s Friday Fun post, as most of these are, is a little silly and a little educational. Because I obviously am avoiding getting any real work accomplished, I worked on a little project that would add a border around a string of text. I often write formatted text to the screen to display information and thought it would be nice to be able to add sometime of border.

My goal was to take a string like “Friday Fun” and write it to the console centered in a bordered box – something like this:

I had to get the length of the string and add 2 to it to allow for a space on either side. The top and bottom lines were as simple as writing the character times the length.

The middle part was simply a matter of concatenating the character and the text.

I then used a here string to create the final result.

And yes, I included a feature where the result could be tabbed or indented a certain number of times. You can find the complete function as a Github gist.

Here are some examples of the function in action.

image

You can border any single line of text. For example, I have a short function to get some basic system information.

I included a parameter to write the result as a formatted string. I can now put a line like this in my PowerShell profile script:

image

Perhaps you can think of other fun ways to add borders to your script or command output. If so, I’d love to hear about it. Enjoy!

2 thoughts on “Friday Fun: Crossing the Border with PowerShell

  1. Hello Jeffrey
    Nice script, i think i’ll use it !
    But, when you do both InsertBlanks and Tab, only the first line of the Body here-strings si tabbed, not the rest.

    Here is how i deal with it :

    Process {
    Write-Verbose “[$((Get-Date).TimeofDay) PROCESS] Processing ‘$text'”
    #get length of text
    $len = $text.Length

    Write-Verbose “[$((Get-Date).TimeofDay) PROCESS] Using a length of $len”
    #define a horizontal line
    $line = $Character * ($len+4)

    $tabs = “`t”*$tab

    if ($insertBlanks) {
    Write-Verbose “[$((Get-Date).TimeofDay) PROCESS] Inserting blank lines”

    $body = @”
    $tabs$character $((” “)*$len) $character
    $tabs$Character $text $Character
    $tabs$character $((” “)*$len) $character
    “@
    }
    else {
    $body = “$tabs$Character $text $Character”
    }

    $out = @”
    $tabs$line
    $body
    $tabs$line
    “@
    #write the result to the pipeline
    $out
    } #process

Comments are closed.