Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Part of a string in powershell

I am trying to extract 2 pieces of information from a string value. The first in from the 4th last to the 2nd last character; the second is from the 2nd last to the last character. This is the code I'm using:

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

    ..
} 

This code keeps throwing an error on the Substring function. The error description is as below:

*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*

How do I use Substring? What should I pass as the correct parameters?

like image 680
Mustafa Salam Avatar asked Feb 02 '16 10:02

Mustafa Salam


People also ask

How can we extract a part from a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do I match a Substring in PowerShell?

Wildcard character (*) matches zero or more characters in the string and if the input string is secular then it gives the boolean output and if it is a string array then the matching strings will be the output as shown below. In the above example, wildcard character (*) matches the string before it (case-insensitive).

How do I find a specific text in PowerShell?

You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.


1 Answers

Substring takes an index and a length parameter. You're passing in an index and an index parameter. If you want two characters from 4th-last character, the code is

$item.Substring($len - 5, 2)

Note that the index is 0-based, not 1-based.

like image 174
Paul Hicks Avatar answered Nov 15 '22 07:11

Paul Hicks