We help IT Professionals succeed at work.

Powershell Script Finds First Result and Quits With Error

Robert Pollick
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

Watch Question

Most Valuable Expert 2019
Most Valuable Expert 2018

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.
$arr = @()
$path = "Path To File"
$pattern = "(?<=.*.@)\w+?(?=,@.*)"

Get-Content $path | Foreach {if ([Regex]::IsMatch($_, $pattern)) {
           $arr += [Regex]::Match($_, $pattern)
$arr | Foreach {$_.Value} | Out-File C:\Temp\Verify_Integrations\CLTest.txt

Open in new window

Search parameters are; .@ and ,@.