PowerShell: How to Get First Line of String in a Variable


You can use the following syntax in PowerShell to get the first line of a string stored in a variable:

$my_string.Split([Environment]::NewLine) | Select -First 1

This particular example will return only the first line from the string stored in the variable named $my_string.

Note that we use the Split method to first split the string into individual elements, using a NewLine as the character to split on.

We then use Select -First 1 to only select the first element that results from this split, which represents the first line of the string.

The following example shows how to use this syntax in practice.

Example: How to Get First Line of String in a Variable Using PowerShell

Suppose we create the following string variable named $my_string in PowerShell:

$my_string = @'
This is line one
This is line two
This is line three
This is line four
'@

The following screenshot shows how to use this syntax in practice:

We can see that this string has a total of four lines.

Suppose that we would like to select only the first line.

We can use the following syntax to do so:

$my_string.Split([Environment]::NewLine) | Select -First 1

The following screenshot shows how to use this syntax in practice:

PowerShell get first line of string in variable

Notice that this returns only the first line from the string stored in the variable named $my_string.

Note: You can return the first N lines from a string by specifying a different number after the -First parameter. For example, you could use Select -First 2 to instead return the first 2 lines from the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get First Line of File
PowerShell: How to Get First Item in Array
PowerShell: How to Get First Character of String

Leave a Reply