18 June 2016

Powershell Tip - Padding Text

Since we use Powershell for just about everything these days, you're sure to end up generating some kind of quick report of something in SharePoint through a simple Powershell script.  Inevitably, the need to pad text comes up.  Powershell makes it easy to left and right pad text variables through the use of the .PadLeft() and .PadRight() .NET methods used as follows:

$str = "My Report Title";
$strPad = $str.PadLeft(20) + ".";
Write-Host $strPad;

The output looks like this:

     My Report Title.

In this case, we were left padding the string to 20 characters.  By default, padding is done with spaces so given the string was already 15 characters long, 5 spaces were added to the front of the string resulting in our output.  The use of the additional period will become apparent as we look at right padding the text as follows:

$strPad = $str.PadRight(20) + ".";
Write-Host $strPad;

The output looks like this:

My Report Title     .

Here you can clearly see the 5 spaces before the period. ;-)
If you want to pad with something other than spaces, you can simply supply the second, optional parameter to PadLeft() or PadRight() specifying the character to be used for padding e.g.

$strPad = $str.PadRight(20, "$") + ".";
Write-Host $strPad;

The output looks like this:

My Report Title$$$$$.

Enjoy!
C


No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...