【发布时间】:2015-09-29 17:31:35
【问题描述】:
我正在执行以下操作以尝试从字符串中获取最后一个字符(在本例中为“0”)。
$string = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\hid\Parameters\0"
$parameter = $string.Substring($string.Length-1, $string.Length)
但我得到了这个与子字符串相关的异常:
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
我理解它的含义,但我不确定为什么我得到的索引和长度是正确的。
即使尝试硬编码也会引发相同的异常:
$parameter = $string.Substring(68, 69)
我有什么遗漏吗?
【问题讨论】:
-
换句话说,您的问题实际上是这样的:“如何在 PowerShell 中获取字符串的最后一个字符?”
-
正确的账单。我只是想更清楚地知道我到底做错了什么,而不是用其他方法来实现它。
-
Substring 方法在documentation 中进行了非常准确的描述。
标签: powershell