A PowerShell Function to Count String Length

Doctor Scripto

Summary: Microsoft Scripting Guy, Ed Wilson, talks about creating a Windows PowerShell function that counts a string length and copies it to the clipboard.

Microsoft Scripting Guy, Ed Wilson, is here. It is hot and humid outside—89 degrees Fahrenheit (32 degrees Celsius) and 75% humidity. That was the great thing about Madrid. Whereas, it was a little hotter (92 degrees Fahrenheit, 33 degrees Celsius), the humidity was less than half the amount we have in Charlotte, North Carolina. The Scripting Wife and I are soaked following a quick trip to the library—and we were not even running. I am sipping a cup of Oolong Green Tea with a bit of cinnamon stick and rose hips. Believe it or not, hot tea on a hot summer day is great. It makes me feel cooler.

My personal criteria for writing a Windows PowerShell script or a Windows PowerShell function is: when a task becomes annoying to me, I spend the time to create a function or a script. At times, the scenario is not all that bad, but eventually it becomes annoying. Today’s function provides such an example. I need to determine the character length of the title for my Hey, Scripting Guy! Blog. To do this, I have been opening Notepad and using the word count feature there. Then I copy the text to the clipboard, close Notepad, and paste it into Word 2013. So here are the steps involved:

  1. Open Notepad.
  2. Type the title.
  3. Note the number of characters.
  4. Copy the title to the clipboard.
  5. Select the entire text.
  6. Type Ctrl-C.
  7. Close Notepad.
  8. Paste the title into Word 2013.

When I list out the number of steps, it seem like a lot of work, but in reality it takes only a minute or two to accomplish. Hmmm…with 730 Hey, Scripting Guy! Blog posts a year, at two minutes each…

That equals 24.5 hours of work!  My new function allows me to accomplish this in less than 15 seconds. Therefore, I save 18.3 hours a year. That is not a bad ROI for a function that took me less than 20 minutes to write.

Creating a function to count letters and copy to the clipboard

So I decided to create a function to count the characters in a string. I am going to add the function to my personal profile so it will always be available.

Start with a function outline

The first thing I do is begin with a function outline as shown here:

Function

{

 

}

Now I need to decide on the name. I always want to use an approved verb. This is easy, because there is the Get-Verb command. At first, I was thinking Count. But when I used the command shown here, there is no Count as an approved verb.

PS C:\> get-verb count

 

PS C:\> 

So this means I will use the verb Get and then add something descriptive. I came up with Get-LetterCount. My function outline now looks like this:

Function Get-LetterCount

{

 

} # End Function Get-LetterCount

Add the function parameter

Now I need to add a parameter that I will use for input. I cast the input as a string because that is the way I anticipate using the function. Here is the Param statement:

Param ([string]$string)

The cool thing is that a string automatically has a Length property so getting the information will be really easy. I want to display the output to the console. I use the Write-Host cmdlet to do this, as shown in this line of code:

Write-Host -ForegroundColor Cyan “string length is” $string.Length

Now, I need to copy the string input to the clipboard. To do this, I use the Clip.exe command. This is easy. Here is the code:

$string | clip.exe

The completed function is shown here:

Function Get-LetterCount

{

 Param ([string]$string)

 Write-Host -ForegroundColor Cyan “string length is” $string.Length

 $string | clip.exe

} # End Function Get-LetterCount

Clean up and make things more usable

I do not want to have to type Get-LetterCount each time I want to use the function. Therefore, I create a really short alias—I mean really short. The letter C. I use Set-Alias instead of New-Alias so that it will overwrite. This is important during testing. It is also something I need to do to ensure that I do not overwrite another alias. Therefore, I use the Get-Alias command first. This is shown here:

PS C:\> Get-Alias c

Get-Alias : This command cannot find a matching alias because an alias with the

name ‘c’ does not exist.

At line:1 char:1

+ Get-Alias c

+ ~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (c:String) [Get-Alias], ItemNotFoundE

   xception

    + FullyQualifiedErrorId : ItemNotFoundException,Microsoft.PowerShell.Commands.G

   etAliasCommand

Cool. Now I can add my new alias as shown here:

Set-Alias -Name c -Value Get-LetterCount

Now I add comment-based Help to the function. This takes me less than 60 seconds because I use my Add-Help function from my Windows PowerShell profile module.

Note For more information about my Windows PowerShell profile module, see Add Power and Functionality to the PowerShell ISE Part 2.

Here is the comment-based Help:

<#

   .Synopsis

    This counts letters in a string

   .Description

    This function counts letters in a string

   .Example

    Get-LetterCount “this is a string

    Returns  string length is 16 and copies text to clipboard

   .Parameter String

    The input as a string

   .Notes

    NAME:  Get-LetterCount

    AUTHOR: ed wilson, msft

    LASTEDIT: 07/03/2013 12:33:28

    KEYWORDS: Scripting Techniques, String Manipulation, Functions

    HSG: HSG-7-10-13

   .Link

     Http://www.ScriptingGuys.com

 #Requires -Version 2.0

 #>

Note  For more information about adding comment-based Help, see Automatically Add Comment-Based Help to your PowerShell Scripts.

Using the Get-LetterCount function

I add the Get-LetterCount function and the alias to my Windows PowerShell ISE profile. I can run the function from inside the ISE or dot source it in the Windows PowerShell console. After the function loads and the alias is created, I use the alias and pass the string as shown here:

PS C:\> c “A PowerShell Function to count string length”

string length is 44

When I call the function, I use the Get-Clipboard cmdlet (from the PSCX module) to verify that my string is indeed on the clipboard. This is shown here:

Image of command output

I can now paste my tile into my Word document. Cool! Now, I need to decide what I will do with the two days I have saved with this function.

The complete script is uploaded to the Script Center Repository: Get String Letter Count Function.

That is all there is to creating a Windows PowerShell function to count string length and copy the string to the clipboard. Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy 

0 comments

Discussion is closed.

Feedback usabilla icon