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:

1
2
3
4
$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.