Powershell

Extract a Substring Using PowerShell – String

PowerShell consists of several data types, including integers, variables, floats, boolean, or strings. A string consists of multiple words that make a meaningful text. While a substring is an adjacent combination of words or a text snippet within a string. A substring can be extracted in PowerShell using a “Substring()” method. Moreover, the “Length” property with the combination of the “Substring()” function can also be used to extract the substring in PowerShell.

This tutorial will observe multiple methods to help resolve the stated query.

How to Extract a Substring Using PowerShell?

These approaches can be used to resolve the above query.

Method 1: Extract a Substring in PowerShell Using “Substring()” Method

The “Substring()” method or function can be utilized to extract a substring. To do so, specify the indexing location in the parentheses, which start from “0”.

Example

This example will demonstrate to extract a substring in PowerShell by utilizing the “Substring()” method:

> $str1 = "It is a Linux Hint Portal."

> $str1.Substring(3,11)

In the above-mentioned code:

  • First, we have assigned a string to a variable “$str1”.
  • Then, concatenate the string-assigned variable with the “Substring()” method and pass

    the starting and ending values separated by commas:

The specified string has been extracted from a string.

Method 2: Extract a Substring Using the “Length” Property in PowerShell

Another way of extracting a substring from a string is by using the “Length” property. It is utilized in order to extract the string’s last characters. For instance, go through the below example.

Example

Execute the following code in PowerShell terminal:

> $str = "This is Linux Hint"

> $str.Substring($str.Length -10)

In the given code, we simply specified the “$str.Length” parameter inside the “Substring()” method and assigned a number to extract a substring from a string:

It can be observed that the substring has been extracted from a string using a “Length” property

Conclusion

The substring can be extracted from a substring in PowerShell using multiple approaches. These approaches include the “Substring()” method or function and the “Length” property. Both of these approaches extract the substring from a string using the character’s indexing numbers. This post has illustrated a complete procedure to extract a substring using PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.