Texts with Maximum Length (Part 2)

Here is another strategy to make sure a text does not exceed a given length. In contrast to our previous tip, this code will not pad spaces in case the text is shorter than the maximum length:

$text = 'this'
$MaxLength = 10
$CutOff = [Math]::Min($MaxLength, $text.Length)

Key is the Min() method which determines the smaller of two values.

Twitter This Tip! ReTweet this Tip!

  • Alternatively, use PowerShell and regex replace as follows;

    $text -replace '(.{10}).+','$1'

    It's only slightly more terse, but I love regex.