PowerShell SubString (Extract Substring) Tutorial

PowerShell provides different methods in order to work with String variables and string values. The substring operation is used to extract some part of the string from a complete string. The substring() method is generally used to extract some part of the string. In this tutorial, we examine how to extract substring with start index and length for strings in Powershell.

Substring() Method Syntax

The substring() method has the following syntax where two parameters can be provided.

STRING.Substring(START,LENGTH)
  • STRING is the string variable or string value where the substring will be extracted.
  • START is the start index of the substring. START parameter is required.
  • LENGTH is the length of the substring which starts with the START parameter.

Extract Substring

The substring can be extracted with the substring method like below. We just provide the start index of the substring. In the following example, we extract the “tect” substring from the complete string “windowstect”. We provide the start index number as 7. The index number starts from 1 .

$name = "windowstect"

$substring = $name.substring(7)

Alternatively, string values also provide the substring() method.

$substring = "windowstect".substring(7)

Extract Substring Dynamically with Length

By default, the substring method starts from the specified start index and continues to the end of the string. But alternatively, we can specify the length of the substring after the specified index.

$name = "windowstect"

$substring = $name.substring(7,2)

Alternatively, we can specify the length of the string for the string values.

$substring = "windowstect".substring(7,2)

Leave a Comment