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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.