tags:

views:

202

answers:

2

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)
+3  A: 

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))
Dmitry Tashkinov
Thanks that will work fine. I was looking for "least" and "greatest" functions and was not aware of this method.
Ethan Post
It is from the .Net standard library. When you don't find a cmdlet that does what you want, check for a method that does this in .Net.
Dmitry Tashkinov
A: 

Thanks to Dmitry for the answer, I turned it into a function and made it so it is 1 based as opposed to 0 based.

function acme-substr ([string]$str, $start, $end) {
   $str.substring($start-1, [System.Math]::Min($str.Length-1, $end))
}

> $foo="0"*20
> $foo
00000000000000000000
> acme-substr $foo 1 5
00000
Ethan Post