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.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.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.