Powershell

The PowerShell Substring: Finding a String Inside a String

A string can contain several substrings inside it. A substring can be found or extracted from a string in PowerShell using several specific commands. The strings can be found by mentioning their starting and ending index numbers inside the “Substring()” method. Moreover, when the “Length” property is concatenated with the “Substring()” method, it helps in finding the string inside a string.

This post will guide you about mentioned query.

How to Find a String Within a String in PowerShell?

These given methods can be applied to fix the mentioned query:

Method 1: Use the “Substring()” Function to Find a String Within/Inside a String

The “Substring()” is a built-in PowerShell method to find or extract a string. In order to find a string, add the starting and ending index number, which starts from 0.

Example
This demonstration will help to find a string within/inside a PowerShell string by utilizing the “Substring()” function:

> $str = "This is a string."
> $str.Substring(0,4)

In the above-stated example:

  • First, assign a string to a variable.
  • After that, concatenate the “Substring()” method with the string assigned variable.
  • Then, pass the starting and ending index number inside “Substring()”:

As it can be observed that the string has been found or extracted successfully.

Method 2: Use the “Length” Property Along with the “Substring()” Function to Find a String Within/Inside a String

Another way of finding the string inside a string is concatenating the “Length” property with the “Substring()” method. It is used to find the last characters of a string.

Example

> $str = "This is a string."
> $str.Substring($str.Length -7)

In the above code, we have utilized the “Length” property concatenated with the string-assigned variable and assigned a number to find a string:

The respective string was found successfully.

Conclusion

The string within/inside a string can be found using the “Substring()” function. For that reason, first, assign a string to a variable and then concatenate the string-assigned variable to the “Substring()” method. Inside the parentheses, add the starting and ending index numbers of the string you want to find or extract. This write-up has discussed in detail to fix the mentioned query.

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.