PowerShell count number of characters in a string

I was just trying to count the number of characters in a string using PowerShell. It seems there is a very simple way to do it. It is a bit different if you are (me include) coming from a C language background like javascript, php or some other similar ones …

So the syntax is as follows:

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$measureObject = $string | Measure-Object -Character;
$count = $measureObject.Character;
Write-Host $count;

I have written the code above on the examples from Scripting Guy! Blog.

  • Stefan Somogyi

    Thanks for this listing. There is an error in the Line “$count = $measureObject.Character”. It should be written “Characters”

  • engageant

    It’s much easier than that. Just use $string.Length.

    • alexkovelsky

      Doesn’t work for my string. It returns 1 while it has to be near 30.

      • You’re likely not measuring a string. You’re likely measuring an array with one item in it that’s a string. `$var.GetType()` to know for sure. All Powershell strings have a single property of `Length` available.