Question:
I’m doing the following to try and get the last character from the string (in this case, “0”).
1 2 3 |
$string = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\hid\Parameters\0" $parameter = $string.Substring($string.Length-1, $string.Length) |
But I’m getting this Substring-related exception:
1 2 3 4 5 6 7 8 9 |
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length" At line:14 char:5 + $parameter = $string.Substring($string.Length-1, $string ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentOutOfRangeException |
I understand its meaning, but I’m not sure why I’m getting given the index and length are correct.
Even attempting to hard code it throws the same exception:
1 2 |
$parameter = $string.Substring(68, 69) |
Is there something I’m missing?
Answer:
Your first argument is that starting position in the string, and the second is the length of the substring, starting at that position. The expression for the 2 characters at positions 68 and 69 would be:
1 2 |
$parameter = $string.Substring(68,2) |