Using String’s Length property
Use string’s length property to get length of String in PowerShell e.g. "Hello World".Length
. System.String
‘s Length property returns number of Characters present in the String.
1 2 3 4 5 |
$blog_name = "Java2blog" # get length of String using length property $blog_name.Length |
Output
1 2 3 |
9 |
Here, we declared a string variable blog_Name
which contains string Java2blog
.
We have used Length
property on the String variable to get length of String in PowerShell.
Length
property returns number of characters present in the String.
You can directly use Length
property even without creating variable.
1 2 3 |
"Java2blog".Length |
Output
1 2 3 |
9 |
You can use Length
property with if
statement to do comparison based on length of String.
For example:
Let’s say you want to check if length of String is greater than 8 or not.
You can use following code:
1 2 3 4 5 6 7 8 |
$blog_name = "Java2blog" # Check if blog_name is greater than 8 Characters if ($blog_name.length -gt 8) { Write-Output "Length of String <code>"Java2blog</code>" is more than 8 Characters" } |
Output
1 2 3 |
Length of String "Java2blog" is more than 8 Characters |
We used -gt
operator to check if String is greater than 8 or not.
Further reading:
Using Measure-Object with Character parameter
Use Measure-Object
cmdlet with Character
parameter to get length of String in PowerShell.
1 2 3 4 5 |
$blog_name = "Java2blog" # get length of String using Measure-Object property $blog_name|Measure-Object -Character |
Output
1 2 3 4 5 |
Lines Words Characters Property ----- ----- ---------- -------- 9 |
Here, we declared a string variable blogName
which contains string "Java2blog" and piped it with Measure-Object
.
Measure-Object
cmdlet provides the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text.
We passed -Character
as parameter to Measure-Object
cmdlet to get total number of characters present in String.
You can also pass -word
as parameter in case you want to count total number of words in String.
1 2 3 4 5 |
$str = "Hello from Java2blog" # get length of String using Measure-Object property $str|Measure-Object -Word -Character |
Output
1 2 3 4 5 |
Lines Words Characters Property ----- ----- ---------- -------- 3 20 |
That’s all about how to get length of String in PowerShell.