This write-up will provide a comprehensive guide to get a substring in PowerShell and in this regard, it will discuss the below-listed learning outcomes:
- How to get a substring in PowerShell?
- Substring() method in PowerShell
- How to use the Substring() method in PowerShell?
So, let’s begin!
How to get a substring in PowerShell?
As we have discussed earlier, a substring is a sub-part of a long/complete string. That’s easy to understand, but the main concern is how to get a substring in PowerShell? Well! In PowerShell, a method named substring() is used to get a substring.
Substring() method in PowerShell
The substring() method takes two parameters, the first one specifies the “starting index” while the other one is “length” which determines the length of the substring (i.e. it specifies how many characters will be returned). The below snippet shows the basic syntax of the substring() method:
The length parameter is optional however if omitted, the remaining string after the starting index will be returned.
How to use the Substring() method?
In this section, we will learn how to get a substring, to do that, we will consider some examples and implement them in PowerShell ISE:
How to get substring in PowerShell?
In the below-given example program, we will utilize the substring() method to get a specific substring “Welcome”:
In the above-given piece of code, we passed “0” and “7” as arguments to the Substring method, consequently, we will get the substring from 0th to 7th index:
The output verified the working of the Substring() method.
How to get a substring placed at last three indexes of a String:
In this example, we will utilize the length() method to get the string’s length:
$findLength = $string.Length
$output = $string.substring($findLength -3)
In this script, we stored a string in variable $string, next we find the string’s length using string.Length() method, and finally, we utilized the substring method to get a substring of specified length and from the specific index:
This is how we can get a substring of the last three characters of a specific string.
A sub-part of a long/complete string is referred to as a substring and to get a substring the Substring() method is used in PowerShell. The Substring() method can have two arguments, the first one specifies the “initial index” while the other one is “length” which determines the length of the substring. In this write-up, we explained how to get a substring in PowerShell with the help of some relevant examples.