Link to home
Start Free TrialLog in
Avatar of Bob
BobFlag for United States of America

asked on

Powershell Script Finds First Result and Quits With Error

This stops on the first line where it finds the "@" and does not continue through the remainder of the text file. Also, when it does complete and gives me the first value that I am looking (120155) for and has an error I am not familiar with.

Error:
Cannot find an overload for "indexOf" and the argument count: "2".
At line:4 char:1
+ $end = $str.indexOf(",@", $start)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest
 
Exception calling "Substring" with "2" argument(s): "startIndex cannot be larger than length of string.
Parameter name: startIndex"
At line:7 char:1
+ $result = $str.substring($start, $length)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentOutOfRangeException
 
120155

PS H:\>


$str = Get-Content C:\Temp\Verify_Integrations\INT_integrations_post2.txt -Encoding Ascii
 
$start = $str.indexOf("@") + 1
$end = $str.indexOf(",@", $start)
$length = $end - $start
 
$result = $str.substring($start, $length)

$result

Open in new window

Avatar of oBdA
oBdA

That happens because the file has more than one line, so $str is an array, not a string.
IndexOf() for an array will look for a single array element matching the string passed, which it won't find.
You can try if adding -Raw to the Get-Content arguments works for you; this will read the file as one single string with line breaks, instead of an array with one element per line:
$str = Get-Content C:\Temp\Verify_Integrations\INT_integrations_post2.txt -Encoding Ascii -Raw

Open in new window

There might be other and better suited ways to extract strings from a file, but for that, you need to provide information about what exactly it is you want to achieve, and what the input file actually looks like.
ASKER CERTIFIED SOLUTION
Avatar of Bob
Bob
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial