ShortenString PowerShell Class Method


While exploring some new data sets for a project, I created class method to handle varied and unexpectedly lengthy text values (e.g., one source is a SQL varchar(max) column). Below, I use some test data to demonstrate how the ShortenString class method can be applied to two text fields: Definition and Comment. The method truncates the string to the nearest whole word (-ish) using a length value passed as the second parameter.

I hope that you find this helpful should you encounter a similar need.

Test Data (CSV)


using namespace System;
using namespace System.Collections;
using namespace System.Collections.Generic;

Class Term
    [string] $Name;
    [string] $Label;
    [string] $Definition;
    [string] $Comment;
    [uri] $URI;
    [string] $Type;

        $this.Name = $name;
        $this.Label = $label;
        $this.Definition = $this.ShortenString($def,50);
        $this.Comment = $this.ShortenString($comment,75);
        $this.URI = $uri;
        $this.Type = $type;

        $str = $str.Replace("'","''");
        if([string]::IsNullOrWhiteSpace($str) -or $str.Length -lt $length)
            return $str;
            [int]$x = $str.LastIndexOf(" ",$length,[StringComparison]::Ordinal);
            return ([string]::Format("{0} {1}",$str.Substring(0,$x),'<a href="#">(more...)</a>')).Trim();

Class TermCollection
    [ArrayList] $Term;
        $this.Term = [ArrayList]::new();
    [void]AddItem([Term] $item)
$tc = [TermCollection]::new();

$sourceData = Import-Csv A:\vocab.csv -Header "Term","URI","Label","Definition","Comment","Type";

foreach($i in $sourceData)
    $t = [Term]::new($i.Term,$i.Label,$i.Definition,$i.Comment,$i.URI,$i.Type);
# demos
return $tc.Term;
return $tc.Term[-2];


Class method allows “fuzzy” string truncation.


  • Test data is from the DCMI metadata list of terms.
  • Class validation is a great feature of PowerShell class properties.
  • I shamelessly borrowed the ShortenString method’s approach from some C# developers and translated into PowerShell.
  • I dummied the HTML anchor tags here to show how stuff can be appended after the string truncation.
  • The Trim() function isn’t needed for the test data, but you should see some of the actual text…
  • No try/catch is used here to show that empty text fields won’t break the code.
  • $str = $str.Replace("'","''") stems from my actual code where output is sent into a SQL database.
    • Sally O’Malley’s happen.
1 Like

Thanks for the share :+1: .

1 Like