0

I have a script which calls an external module. The external module loops through a list of websites and searches each page for certain terms. It denotes the website, webpage, term found and stores them into an array which it then sends back to the main script once all the sites are searched. The script is great when the module has completed the array (in the module looks perfect) so if I print $resultArray it just lists the result. However once I'm back in the main script under the line that says $resultArray = ExternalFunction -parameters cyz and I print the result array the connection string results for each site have been appended to the beginning of the actual results throwing off the whole CSV file and making my actual results not come out because the columns don't exist in a connection string. So I have no idea why or how it is putting the connection string out there or how to stop it.

My external function is pretty much just

Function searchPages(sites){

$sitelist=Get-Sites

foreach($site in $sitelist)
{
  $page = GetPageContent
  If (KeywordFound)
  {
    $outputData = Get-OutputData $page
    $listMatches = SetMatchData  -searchcontent -url -outputData
    $resultArray += listMatches
  }
}
return $resultArray 
}

Anyway at the end of this function $resultArray is perfect just what I want. It isn't until it is passed back to the main script. Where I have this:

$resultArray = SearchPages -sites c:\sites.csv

And when I check $resultArray AFTER I just checked it in the module and it was fine now it is prepended with # of site connections (depending om the number of sites in the list). How do I make it just return the array and not append any extra data? What am I missing on my external module?

TA_US
  • 11
  • 5
  • 1
    Based on the code as shown, there's no explanation for your symptom, but I suspect that in your real code there's some statement whose output isn't captured and therefore implicitly contributes to the function's output. Note that it isn't just `return` that determines what a function outputs. Perhaps [this answer](https://stackoverflow.com/a/70928244/45375) helps. – mklement0 May 26 '23 at 21:17
  • 1
    As an aside: Extending arrays in a loop with `+=` is inefficient, because a _new_ array must be created behind the scenes _in every iteration_, given that arrays are of fixed size; a much more efficient approach is to use a `foreach` loop as an _expression_ and let PowerShell itself collect the outputs in an array: `[array] $outputs = foreach (...) { ... }` - see [this answer](https://stackoverflow.com/a/60708579/45375). – mklement0 May 26 '23 at 21:18

0 Answers0