Avatar of Bob
Flag 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.

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

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)


Open in new window


Avatar of undefined
Last Comment

8/22/2022 - Mon

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.

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.