6

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?

1

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.