Tuesday, September 15, 2009

Trim a string to a specific number of characters

While creating AD groups I ran into the problem of having group names over 64 chars.  AD does not like this and errors during the creation.  So, what was my answer?  Trim the group name string to the 64 char limit.  Here is my one-liner to trimg a string down to n' chars.
 
ONELINER

"Your_Text_To_Trim" | % { $_.TrimEnd($_.Substring(10))}

PEICE BY PEICE
"Your_Text_To_Trim"
This you can substitute any string here.  That could be simple text or or a string variable.

| %
All piped elements (using the | is called piping) must have an operator to create a new object.  Foreach-Object (%) will create the $_ object that we will use

$_.TrimEnd
TrimEnd() is a string method for removing specific text from the end of a string.  This does take specific text, not wildcards.

$_.Substring(10)
Here is were we find the text to remove.  Substring() is another string method that extracts the characters after the given position.  In this case "To_Trim"

EXPANDED
$text = "Your_Text_To_Trim"
$substring = $text.Substring(10)
$trim = $text.TrimEnd($substring)
$trim
 code: copy : expand : collapse

This could be done through the expanded code.  Notice that we do not need to use the Foreach-Object cmdlet.  Once again, we had to use this to create the Object $_ to manipulate.

NOTE
When using the TrimEnd() method it will truncate all spaces and underscores if they are the last character of the string AFTER the trim is completed.  You will probably notice the output above would be "Your_Text" instead of "Your_Text_"

ALIASES
% = Foreach-Object

0 comments: