0

I am trying to extract list of NPM packages from each GitHub.

I have a iteration that does the following:

  • Search for package-lock.json files in each GitHub repo for an Organization
  • Iterate through all package-lock.json file for each repo and get it's content (Always Base64 Encoded)
  • Decode the content and replace a few characters if found in file
  • Pipe content to ConvertFrom-Json to have it as an object
  • Extract dependencies property in each content

All these works when handled without iteration however the iteration does not work as expected. For a particular repo with two "package-lock.json", It does not output the list of packages for the first "package-lock.json" file.

However the output for the first and second file are all concatenated in the output for the second file in the iteration.

$packagejsonFiles = Invoke-RestMethod ('https://api.github.com/search/code?q=filename:package-lock.json+extension:json+repo:' + $OrgName + '/' + $repo.name) -Method Get -Headers $headers -ErrorAction SilentlyContinue

foreach($packagejsonFile in $packagejsonFiles.items){ #Start foreach on NPM files
    $PackagelockFile = Invoke-RestMethod ('https://api.github.com/repos/' + $OrgName + '/' + $repo.name + '/git/blobs/' + $packagejsonFile.sha) -Method GET -Headers $headers
            
    $PackagelockFileContents = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($PackagelockFile.content))

    $packagejsonFilesContents = $PackagelockFileContents.Replace('" "', '""').Replace('""', "`"name`"")

    $conFile = ConvertFrom-Json -InputObject $packagejsonFilesContents 

#(At this point, it does not provide any output for first file.)**

            $confile.dependencies.PSObject.Properties | Select-Object  Name,
            @{
                Name = 'Version'
                Expression = { $_.Value.Version }
            }, @{
                Name = 'Resolved'
                Expression = { $_.Value.Resolved }
            }
            Write-Host ""
            $Index++
            
        }

The Output

Please any help to fix this will be appreciated. I need the output to be available per file per iteration

  • The code sample looks incomplete, please add the code that does output and close the `foreach` block. – zett42 Feb 11 '22 at 20:19
  • @zett42 I have added the rest of the code snippet. Thanks – Caleb Adepoju Feb 11 '22 at 20:27
  • See if [this answer](https://stackoverflow.com/a/43691123/45375) helps (start with the 2nd section). If so, we can close your question as a duplicate. – mklement0 Feb 11 '22 at 22:41
  • After your `Invoke-RestMethod` have you tried maybe using a `sleep -s 2`, to give the response time to return before you use the objects from the response? I would try that, and if it works let me know I'll post as answer to be accepted. – shadow2020 Feb 12 '22 at 00:22

0 Answers0