PowerShell TruncateAtWhitespace Function

Here’s a TruncateAtWhitespace function that takes an incoming parameter value and an incoming max length, and returns a substring broken at a whitespace position.  This way if you have “Lance has a blog” and you need to truncate it to 8 characters or less, you get “Lance” instead of “Lance ha”.

function TruncateAtWhitespace{
    param(
        [string]$value,
        [int]$maxlength=200
    )
    $maxlength-=3; #allow for "..." suffix
    if ($value.Length -le $maxlength) {
      return ($value + "...");
    }
    $closestwhitespaceindex = [int]$value.Substring(0, $maxlength).LastIndexOf(" ");
    if ($closestwhitespaceindex -gt 0) {
      $value = $value.Substring(0, $closestwhitespaceindex) + "...";
    } else {
      $value = $value.Substring(0, $maxlength);
    }
    return $value;
}
Technorati Tags:
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Monday, August 16, 2010 3:30 PM

Feedback

No comments posted yet.

Your comment:





 
 

Copyright © Lance Robinson

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski