小编Mus*_*lam的帖子

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

我试图从字符串值中提取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)

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

string powershell substring

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

powershell ×1

string ×1

substring ×1