[英]Extract Part of a string in powershell
我試圖從字符串值中提取2條信息。 從最后的第4個到第2個最后一個角色的第一個; 第二個是從最后一個到最后一個角色。 這是我正在使用的代碼:
foreach ($item in $List)
{
$len = $item.Length
$folder1 = $item.Substring(($len - 2), $len)
$folder2 = $item.Substring(($len - 4), ($len - 2))
..
}
此代碼不斷在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*
我如何使用Substring? 我應該傳遞什么作為正確的參數?
Substring
采用索引和長度參數。 您正在傳入索引和索引參數。 如果你想要倒數第4個字符中的兩個字符,那么代碼是
$item.Substring($len - 5, 2)
請注意,索引是從0開始的,而不是從1開始的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.