在Powershell中提取字符串的一部分

Mus*_*lam 3 string powershell substring

我试图从字符串值中提取2条信息。从第4个倒数到第2个倒数第一个;第二个是从倒数第二个到最后一个字符。这是我正在使用的代码:

foreach ($item in $List)
{
    $len = $item.Length
    $folder1 = $item.Substring(($len - 2), $len)
    $folder2 = $item.Substring(($len - 4), ($len - 2))

    ..
} 
Run Code Online (Sandbox Code Playgroud)

此代码不断在Substring函数上引发错误。错误描述如下:

*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*
Run Code Online (Sandbox Code Playgroud)

如何使用子串?我应该通过什么作为正确的参数?

Pau*_*cks 5

Substring接受一个索引和一个长度参数。您正在传递索引和索引参数。如果您要从倒数第4个字符中选择两个字符,则代码为

$item.Substring($len - 5, 2)
Run Code Online (Sandbox Code Playgroud)

请注意,索引是从0开始的,而不是从1开始的。