Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: How to limit string to N characters?

Tags:

powershell

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)
like image 414
Ethan Post Avatar asked Feb 25 '10 18:02

Ethan Post


People also ask

How do I trim a string in PowerShell?

One of the most common ways to trim strings in PowerShell is by using the trim() method. Like all of the other trimming methods in PowerShell, the trim() method is a member of the System. String . NET class.

How do I use TrimStart in PowerShell?

TrimStart([Characters_to_remove]) Key Characters_to_remove The characters to remove from the beginning and/or end of the string. Multiple characters can be specified. The order of the characters does not affect the result. By default trim() will remove leading and trailing spaces and leading and trailing line breaks.

How do I remove part of a string in PowerShell?

To remove the first character from the string, call the PowerShell string Remove() method and pass input arguments as startIndex and count.


2 Answers

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))
like image 57
Dmitry Tashkinov Avatar answered Sep 28 '22 05:09

Dmitry Tashkinov


Using the substring function has it's limitations and requires you to first capture the length of the string. Granted this does work you can do it without that limitation.

The following will return the first 5 characters of the string

"1234567890"[0..4] -join ""     # returns the string '12345'

And this will work on strings that are shorter than desired length

"1234567890"[0..1000] -join ""  # returns the string '1234567890'
like image 20
Ro Yo Mi Avatar answered Sep 28 '22 07:09

Ro Yo Mi