Getting the Number of Lines in a String

by Sep 15, 2014

All PowerShell Versions

Here is a clever trick how to find out how many lines a string (not a string array!) contains:

$text = @'
This is some
sample text
Let's find out
the number of lines.
'@

$text.Length - $text.Replace("`n",'').Length + 1 

Technically, the example uses a here-string to create the multi-line string, but this is just an example. It works for all kinds of strings, regardless of origin.

Twitter This Tip! ReTweet this Tip!