PowerShell: How to Get First Character of String


You can use the following syntax in PowerShell to get the first character of a string:

$my_string.Substring(0, [Math]::Min($my_string.Length, 1))

This particular example gets the first character in the string variable named $my_string.

Note: The second argument in the Substring() method specifies that the last character we would like to return should be the minimum of either the length of the entire string or the value specified in the second argument of the Min() method.

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

Example: How to Get First Character of String in PowerShell

Suppose we have the following string of interest:

  • “Hello everyone, welcome to the party.”

We can use the following syntax to get only the first character of this string:

$my_string = "Hello everyone, welcome to the party."
$my_string.Substring(0, [Math]::Min($my_string.Length, 1))

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

PowerShell get first character in string

This returns “H” which is indeed the first character in the string.

To get the first 5 characters in the string, we could simply change the 1 to a 5 within the Min() method:

$my_string = "Hello everyone, welcome to the party."
$my_string.Substring(0, [Math]::Min($my_string.Length, 5))

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

PowerShell get first n characters in string

This returns “Hello” which indeed represents the first five characters in the string.

Suppose instead that we tried to get the first 500 characters in the string:

$my_string = "Hello everyone, welcome to the party."
$my_string.Substring(0, [Math]::Min($my_string.Length, 500))

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

Since there are not 500 characters in this string, it simply returns the length of the entire string.

Related Tutorials

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

PowerShell: How to Get Last Item in Array
PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File

Leave a Reply