I just received a PowerShell question from a community member by direct message through Twitter… His question was: ”struggling to determine the length of a string with contains a numbers as value in PowerShell … any tips?”.
This is actually a very good question since this is something that is done quite a lot And as I came to think about it, I’ve never written anything about that topic so here I am
Let’s take a string you’ve filled with a bunch of characters…
$string = 12345678
When you want to know the number of characters in this string, you can get this information with the following line:
$string | measure-object –character
But… that gives you a few column names and the number of characters…
so still too much information (I don’t want those column names, just the number of characters!). To just get the number of characters, use the following line:
$string | measure-object -character | select -expandproperty characters
Which in turn you can put in it’s own variable:
$characters = $string | measure-object -character | select -expandproperty characters
Thanks, Jeff. I appreciate the tip.
Hi Jeff. Here’s my two cents on this post:
The value $string is not a string at all, it’s an integer. If the intent was for the value to be a string the syntax should be [string]$string = 12345678 or $string = ‘12345678’. If $string is indeed a string then the number of characters can be detemined more easily by $string.length and if $string contains an integer it would be $string.ToString().Length
Hi Micah,
You’re correct, thanks for commenting.
Jeff.