To get PowerShell substring after a character in the given string, use the IndexOf method over the string to get the position of the character. Use the position in PowerShell substring as the start index to get a substring.
PowerShell substring() method returns the part of the string. IndexOf method in String gets the first occurrence of a character in the string and returns the position.
In this article, we will discuss how to extract substring after a character in PowerShell string using the Substring and IndexOf methods.
Find PowerShell Substring After a Character
Use the IndexOf method to find the first occurrence of a character, it returns the index position of a character.
As we want to get a substring after a character, hence add 1 to the index position retrieved from the IndexOf
method.
Let’s consider, that the $str
contains the string in PowerShell. We want to get substring 5002 from the given string.
To get the index of the character colon (:) and stores its index position in the variable $position
.
To extract the substring after a character colon (:), use its position and add +1 to it so that PowerShell Substring() method starts from the position.
$str = "10.1.0.1:5002" $position = $str.IndexOf(":") $str.Substring($position+1)
In the above PowerShell script, it returns a substring as 5002.
The output of the above script is:
Conclusion
I hope the above article on how to find substring after a character in PowerShell using the Substring() method is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.