powershell

PowerShell: How to limit string to N characters?


substring complains when I try to limit a string to 10 characters which is not 10 or more characters in length. I know I can test the length but I would like to know if there is a single cmdlet which will do what I need.

PS C:\> "12345".substring(0,5)
12345

PS C:\> "12345".substring(0,10)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At line:1 char:18
+ "12345".substring( <<<< 0,10)

Solution

  • Do you need exactly a cmdlet? I wonder why you don't like getting length. If it's part of a script, then it looks fine.

    $s = "12345"
    $s.substring(0, [System.Math]::Min(10, $s.Length))