stringpowershellsubstring

Substring in PowerShell to truncate string length


Is it possible in PowerShell, to truncate a string, (using SubString()?), to a given maximum number of characters, even if the original string is already shorter?

For example:

foreach ($str in "hello", "good morning", "hi") { $str.subString(0, 4) }

The truncation is working for hello and good morning, but I get an error for hi.

I would like the following result:

hell
good
hi

Solution

  • You need to evaluate the current item and get the length of it. If the length is less than 4 then use that in the substring function.

    foreach ($str in "hello", "good morning", "hi") {
        $str.subString(0, [System.Math]::Min(4, $str.Length)) 
    }