I am trying to extract 2 pieces of information from a string value. The first in from the 4th last to the 2nd last character; the second is from the 2nd last to the last character. This is the code I'm using:
foreach ($item in $List)
{
$len = $item.Length
$folder1 = $item.Substring(($len - 2), $len)
$folder2 = $item.Substring(($len - 4), ($len - 2))
..
}
This code keeps throwing an error on the Substring function. The error description is as below:
*Exception calling "Substring" with "2" argument(s): "Index and length must refer to a
location within the string.
Parameter name: length"
At line:7 char:1
+ $str.Substring($flen - 2, $slen)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException*
How do I use Substring? What should I pass as the correct parameters?
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
Wildcard character (*) matches zero or more characters in the string and if the input string is secular then it gives the boolean output and if it is a string array then the matching strings will be the output as shown below. In the above example, wildcard character (*) matches the string before it (case-insensitive).
You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.
Substring
takes an index and a length parameter. You're passing in an index and an index parameter. If you want two characters from 4th-last character, the code is
$item.Substring($len - 5, 2)
Note that the index is 0-based, not 1-based.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With