PSGithubSearch.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
#Requires -Version 4

Function Find-GitHubRepository {
<#
.SYNOPSIS
    Searches repositories on GitHub.com based on the specified search keyword(s) and parameters.
     
.DESCRIPTION
    Uses the GitHub search API to find repositories on GitHub.com based on the specified search keyword(s) and parameters.
 
    This API's documentation is available here : https://developer.github.com/v3/search/
 
    NOTE : The GitHub Search API limits each search to 1,000 results and the number of requests to 10 per minute.
     
.PARAMETER Keywords
    One or more keywords to search.
 
.PARAMETER Language
    To search repositories based on the language they are written in.
 
.PARAMETER In
    To qualify which field is searched. With this qualifier you can restrict the search to just the repository name, description, or readme.
    If not specified, the default behaviour is to search in both the name, description and readme.
 
.PARAMETER SizeKB
    To search repositories that match a certain size (in kilobytes).
 
.PARAMETER Fork
    Filters whether forked repositories should be included ( if the value is 'true' ) or only forked repositories should be returned ( if the value is 'only' ).
    If this parameter is not specified, the default behaviour is to exclude forks.
 
.PARAMETER User
    To Limit searches to repositories owned by a specific user.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Stars
    To filter repositories based on the number of stars.
 
.PARAMETER SortBy
    To specify on which field the results should be sorted on : number of stars, forks or last updated date.
    By default, the results are sorted by best match.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'TCP' -Language 'Python'
 
    Searches GitHub repositories which have the word "TCP" in their name or description or readme and are written in Python.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'TCP' -Language 'Python' -In name
 
    Searches GitHub repositories which have the word "TCP" in their name and are written in Python.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'UDP' -In description -SizeKB '>200'
 
    Searches GitHub repositories which have the word "UDP" in their description and are larger than 200 kilobytes.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'PowerShell-Docs' -In name -Fork only
 
    Searches forks which have the word "PowerShell-Docs" in their name.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'script' -User 'MathieuBuisson'
 
    Searches GitHub repositories which have the word "script" in their name or description or readme and are owned by the user MathieuBuisson.
 
.EXAMPLE
    Find-GitHubRepository -Keywords 'disk','space' -In readme -Stars '>=10'
 
    Searches GitHub repositories which have both words "disk" and "space" in their readme and have 10 or more stars.
 
.EXAMPLE
    Find-GitHubRepository -SortBy stars -In name -Language 'PowerShell' -Keywords 'Pester'
 
    Searches GitHub repositories written in PowerShell which have the word "Pester" in their name and sorts them by the number of stars (descending order).
 
.NOTES
    Author : Mathieu Buisson
     
.LINK
    https://github.com/MathieuBuisson/PSGithubSearch
#>

    [CmdletBinding()]
    
    Param(
        [Parameter(Mandatory=$True,Position=0)]
        [string[]]$Keywords,

        [Parameter(Position=1)]
        [string]$Language,

        [Parameter(Position=2)]
        [ValidateSet('name','description','readme')]
        [string]$In,

        [Parameter(Position=3)]
        [ValidatePattern('^[\d<>][=\d]\d*$')]
        [string]$SizeKB,

        [Parameter(Position=4)]
        [ValidateSet('true','only')]
        [string]$Fork,

        [Parameter(Position=5)]
        [string]$User,

        [Parameter(Position=6)]
        [ValidatePattern('^[\d<>][=\d]\d*$')]
        [string]$Stars,

        [Parameter(Position=7)]
        [ValidateSet('stars','forks','updated')]
        [string]$SortBy
    )

    [string]$KeywordsString = $Keywords -join '+'
    [string]$QueryString = 'q=' + $KeywordsString

    If ( $Language ) {
        $QueryString += '+language:' + $Language
    }
    If ( $In ) {
        $QueryString += '+in:' + $In
    }
    If ( $SizeKB ) {
        $QueryString += '+size:' + $SizeKB
    }
    If ( $Fork ) {
        $QueryString += '+fork:' + $Fork
    }
    If ( $User ) {
        $QueryString += '+user:' + $User
    }
    If ( $Stars ) {
        $QueryString += '+stars:' + $Stars
    }
    If ( $SortBy ) {
        $QueryString += "&sort=$SortBy"
    }

    # Using the maximum number of results per page to limit the number of requests
    $QueryString += '&per_page=100'

    $UriBuilder = New-Object System.UriBuilder -ArgumentList 'https://api.github.com'
    $UriBuilder.Path = 'search/repositories' -as [uri]
    $UriBuilder.Query = $QueryString

    $BaseUri = $UriBuilder.Uri
    Write-Verbose "Constructed base URI : $($BaseUri.AbsoluteUri)"

    $Response = Invoke-WebRequest -Uri $BaseUri
    If ( $Response.StatusCode -ne 200 ) {

        Write-Warning "The status code was $($Response.StatusCode) : $($Response.StatusDescription)"
    }
    $NumberOfPages = Get-NumberofPage -SearchResult $Response
    Write-Verbose "Number of pages for this search result : $($NumberOfPages)"

    Foreach ( $PageNumber in 1..$NumberOfPages ) {

        $ResultPageUri = $BaseUri.AbsoluteUri + "&page=$($PageNumber.ToString())"

        Try {
            $PageResponse  = Invoke-WebRequest -Uri $ResultPageUri -ErrorAction Stop
        }
        Catch {
            Throw $_.Exception.Message
        }

        # The search API limits the number of requests to 10 requests per minute and per IP address (for unauthenticated requests)
        # We might be subject to the limit on the number of requests if we run function multiple times in the last minute
        $RemainingRequestsNumber = $PageResponse.Headers.'X-RateLimit-Remaining' -as [int]
        Write-Verbose "Number of remaining API requests : $($RemainingRequestsNumber)."

        If ( $RemainingRequestsNumber -le 1 ) {
            Write-Warning "The search API limits the number of requests to 10 requests per minute"
            Write-Warning "Waiting 60 seconds before processing the remaining result pages because we have exceeded this limit."
            Start-Sleep -Seconds 60
        }
        $PageResponseContent = $PageResponse.Content | ConvertFrom-Json

        Foreach ( $PageResult in $PageResponseContent.items ) {

            $PageResult.psobject.TypeNames.Insert(0,'PSGithubSearch.Repository')
            $PageResult
        }
    }
}

Function Find-GitHubCode {
<#
.SYNOPSIS
    Searches file contents on GitHub.com based on the specified search keyword(s) and parameters.
     
.DESCRIPTION
    Uses the GitHub search API to find code in files on GitHub.com based on the specified search keyword(s) and parameters.
 
    This API's documentation is available here : https://developer.github.com/v3/search/
 
    NOTE : Due to the complexity of searching code, the GitHub Search API has a few restrictions on how searches are performed :
        - Only the default branch is considered. In most cases, this will be the master branch.
        - Only files smaller than 384 KB are searchable.
        - Only repositories with fewer than 500,000 files are searchable.
 
.PARAMETER Keywords
    One or more keywords or code snippet to search.
 
.PARAMETER User
    To Limit searches to code owned by a specific user.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Repo
    To Limit searches to code in a specific repository.
    The value of this parameter must match exactly with the full name of an existing GitHub repository, formatted as : Username/RepoName.
 
.PARAMETER Language
    To search code based on the language it is written in.
 
.PARAMETER In
    To qualify which field is searched. With this qualifier you can restrict the search to files contents or to files paths.
    If not specified, the default behaviour is to search in both files contents and paths.
         
.PARAMETER SizeBytes
    To search only files that match a certain size (in bytes).
 
.PARAMETER Fork
    Filters whether forked repositories should be included in the search.
    By default, forks are not searched unless the fork has more stars than the parent repository.
 
.PARAMETER FileName
    Filters the search to files with a name containing the string specified via this parameter.
 
.PARAMETER Extension
    Filters the search to files with the specified extension.
 
.PARAMETER SortByLastIndexed
    Sorts the results by how recently a file has been indexed by the GitHub search infrastructure.
    By default, the results are sorted by best match.
 
.EXAMPLE
    Find-GitHubCode -User 'MathieuBuisson' -Keywords 'SupportsShouldProcess' -Extension 'psm1'
 
    Finds the .psm1 files which contain the code 'SupportsShouldProcess' in repositories from the user 'MathieuBuisson'.
 
.NOTES
    Author : Mathieu Buisson
     
.LINK
    https://github.com/MathieuBuisson/PSGithubSearch
#>

    [CmdletBinding(DefaultParameterSetName='User')]
    
    Param(
        [Parameter(Mandatory=$True,Position=0)]
        [string[]]$Keywords,

        [Parameter(Position=1,ParameterSetName='User')]
        [string]$User,

        [Parameter(Position=1,ParameterSetName='Repo')]
        [ValidatePattern('^[a-zA-Z]+/[a-zA-Z]+')]
        [string]$Repo,

        [Parameter(Position=2)]
        [string]$Language,

        [Parameter(Position=3)]
        [ValidateSet('file','path')]
        [string]$In,

        [Parameter(Position=4)]
        [ValidatePattern('^[\d<>][=\d]\d*$')]
        [string]$SizeBytes,

        [Parameter(Position=5)]
        [switch]$Fork,

        [Parameter(Position=6)]
        [string]$FileName,

        [Parameter(Position=7)]
        [string]$Extension,

        [Parameter(Position=8)]
        [switch]$SortByLastIndexed
    )

    # Cleaning up the value of $Extension if the user puts a "dot" at the beginning
    If ( $Extension -match '^\.' ) {
        $Extension = $Extension.TrimStart('.')
    }

    [string]$KeywordsString = $Keywords -join '+'
    [string]$QueryString = 'q=' + $KeywordsString

    If ( $Language ) {
        $QueryString += '+language:' + $Language
    }
    If ( $In ) {
        $QueryString += '+in:' + $In
    }
    If ( $SizeBytes ) {
        $QueryString += '+size:' + $SizeBytes
    }
    If ( $Fork ) {
        $QueryString += '+fork:true'
    }
    If ( $User ) {
        $QueryString += '+user:' + $User
    }
    If ( $Repo ) {
        $QueryString += '+repo:' + $Repo
    }
    If ( $FileName ) {
        $QueryString += '+filename:' + $FileName
    }
    If ( $Extension ) {
        $QueryString += '+extension:' + $Extension
    }
    If ( $SortByLastIndexed ) {
        $QueryString += "&sort=indexed"
    }

    # Using the maximum number of results per page to limit the number of requests
    $QueryString += '&per_page=100'

    $UriBuilder = New-Object System.UriBuilder -ArgumentList 'https://api.github.com'
    $UriBuilder.Path = 'search/code' -as [uri]
    $UriBuilder.Query = $QueryString

    $BaseUri = $UriBuilder.Uri
    Write-Verbose "Constructed base URI : $($BaseUri.AbsoluteUri)"

    $Response = Invoke-WebRequest -Uri $BaseUri
    If ( $Response.StatusCode -ne 200 ) {

        Write-Warning "The status code was $($Response.StatusCode) : $($Response.StatusDescription)"
    }
    $NumberOfPages = Get-NumberofPage -SearchResult $Response
    Write-Verbose "Number of pages for this search result : $($NumberOfPages)"

    Foreach ( $PageNumber in 1..$NumberOfPages ) {

        $ResultPageUri = $BaseUri.AbsoluteUri + "&page=$($PageNumber.ToString())"

        Try {
            $PageResponse  = Invoke-WebRequest -Uri $ResultPageUri -ErrorAction Stop
        }
        Catch {
            Throw $_.Exception.Message
        }

        # The search API limits the number of requests to 10 requests per minute and per IP address (for unauthenticated requests)
        # We might be subject to the limit on the number of requests if we run function multiple times in the last minute
        $RemainingRequestsNumber = $PageResponse.Headers.'X-RateLimit-Remaining' -as [int]
        Write-Verbose "Number of remaining API requests : $($RemainingRequestsNumber)."

        If ( $RemainingRequestsNumber -le 1 ) {
            Write-Warning "The search API limits the number of requests to 10 requests per minute"
            Write-Warning "Waiting 60 seconds before processing the remaining result pages because we have exceeded this limit."
            Start-Sleep -Seconds 60
        }
        $PageResponseContent = $PageResponse.Content | ConvertFrom-Json

        Foreach ( $PageResult in $PageResponseContent.items ) {            

            $PageResult.psobject.TypeNames.Insert(0,'PSGithubSearch.Code')
            $PageResult
        }
    }
}

Function Find-GitHubIssue {
<#
.SYNOPSIS
    Searches issues and pull requests on GitHub.com based on the specified search keyword(s) and parameters.
     
.DESCRIPTION
    Uses the GitHub search API to find issues and/or pull requests on GitHub.com based on the specified search keyword(s) and parameters.
 
    This API's documentation is available here : https://developer.github.com/v3/search/
 
.PARAMETER Keywords
    To search issues and/or pull requests containing the specified keyword(s) in their title, body or comments.
 
.PARAMETER Type
    To restrict the search to issues only or pull requests only.
    By default, both are searched.
 
.PARAMETER In
    To qualify which field is searched for the specified keyword(s). With this qualifier you can restrict the search to the title, body or comments of issues and pull requests.
    By default, all these fields are searched for the specified keyword(s).
 
.PARAMETER Author
    To Limit searches to issues or pull requests created by a specific user.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Assignee
    To Limit searches to issues or pull requests assigned to a specific user.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Mentions
    To Limit searches to issues or pull requests in which a specific user is mentioned.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Commenter
    To Limit searches to issues or pull requests in which a specific user commented.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER Involves
    To Limit searches to issues or pull requests which were either created by a specific user, assigned to that user, mention that user, or were commented on by that user.
    If the value of this parameter doesn't match exactly with an existing GitHub user name, it throws an error.
 
.PARAMETER State
    Filter issues and/or pull requests based on whether they are open or closed.
 
.PARAMETER Labels
    Filters issues and/or pull requests based on their labels.
    Limitation : this doesn't retrieve labels containing spaces or forward slashes.
 
    If multiple labels are specified, only issues which have all the specified labels are returned.
 
.PARAMETER No
    To Limit searches to issues or pull requests which are missing certain metadata : label, milestone or assignee.
 
.PARAMETER Language
    Searches for issues and/or pull requests within repositories that match a certain language.
 
.PARAMETER Repo
    To Limit searches to issues and/or pull requests within a specific repository.
 
.PARAMETER SortBy
    To specify on which field the results should be sorted on : number of comments, creation date or last updated date.
    By default, the results are sorted by best match.
 
.EXAMPLE
    $PowershellPR = Find-GitHubIssue -Type pr -Repo 'powershell/powershell'
    $PowershellPR | Group-Object -Property { $_.User.login } | Sort-Object -Property Count -Descending | Select-Object -First 10
 
    Gets the username of the 10 largest contributors to the PowerShell repository, in number of pull requests.
 
.NOTES
    Author : Mathieu Buisson
     
.LINK
    https://github.com/MathieuBuisson/PSGithubSearch
#>

    [CmdletBinding()]
    
    Param(
        [Parameter(Position=0)]
        [string[]]$Keywords,

        [Parameter(Position=1)]
        [ValidateSet('issue','pr')]
        [string]$Type,

        [Parameter(Position=2)]
        [ValidateSet('title','body','comments')]
        [string]$In,

        [Parameter(Position=3)]
        [string]$Author,

        [Parameter(Position=4)]
        [string]$Assignee,

        [Parameter(Position=5)]
        [string]$Mentions,

        [Parameter(Position=6)]
        [string]$Commenter,

        [Parameter(Position=7)]
        [string]$Involves,

        [Parameter(Position=8)]
        [ValidateSet('open','closed')]
        [string]$State,

        [Parameter(Position=9)]
        [string[]]$Labels,

        [Parameter(Position=10)]
        [ValidateSet('label','milestone','assignee')]
        [string]$No,

        [Parameter(Position=11)]
        [string]$Language,

        [Parameter(Position=12)]
        [string]$Repo,

        [Parameter(Position=13)]
        [ValidateSet('comments','created','updated')]
        [string]$SortBy
    )

    If ( $Keywords ) {
        $KeywordFilter = $Keywords -join '+'
    }
    If ( $Labels ) {
        $LabelsFilterArray = Foreach ( $Label in $Labels ) { 'label:{0}' -f $Label }
        [string]$LabelsFilter = If ( $LabelsFilterArray.Count -gt 0 ) { $LabelsFilterArray -join '+' }
    }

    # The remaining filters can be used the same way to build their respective filter strings
    If ( $PSBoundParameters.ContainsKey('Keywords') ) {
        $Null = $PSBoundParameters.Remove('Keywords')
    }
    If ( $PSBoundParameters.ContainsKey('Labels') ) {
        $Null = $PSBoundParameters.Remove('Labels')
    }
    If ( $PSBoundParameters.ContainsKey('SortBy') ) {
        $Null = $PSBoundParameters.Remove('SortBy')
    }    
    [System.Collections.ArrayList]$JoinableFilterStrings = @()
    Foreach ( $ParamName in $PSBoundParameters.Keys ) {
        
        $JoinableFilterString = '{0}:{1}' -f $ParamName.ToLower(), $PSBoundParameters[$ParamName]
        $Null = $JoinableFilterStrings.Add($JoinableFilterString)
    }
    $JoinedFilterStrings = If ($JoinableFilterStrings.Count -gt 0) {$JoinableFilterStrings -join '+'}
    $JoinedFilter = ($KeywordFilter, $JoinedFilterStrings, $LabelsFilter -join '+').Trim('+')
    $QueryString = 'q={0}' -f $JoinedFilter

    If ( $SortBy ) {
        $QueryString += '&sort={0}' -f $SortBy
    }
    $QueryString += '&per_page=100'
    
    $UriBuilder = New-Object System.UriBuilder -ArgumentList 'https://api.github.com'
    $UriBuilder.Path = 'search/issues' -as [uri]
    $UriBuilder.Query = $QueryString

    $BaseUri = $UriBuilder.Uri
    Write-Verbose "Constructed base URI : $($BaseUri.AbsoluteUri)"

    $Response = Invoke-WebRequest -Uri $BaseUri
    If ( $Response.StatusCode -ne 200 ) {

        Write-Warning "The status code was $($Response.StatusCode) : $($Response.StatusDescription)"
    }
    $NumberOfPages = Get-NumberofPage -SearchResult $Response
    Write-Verbose "Number of pages for this search result : $($NumberOfPages)"

    Foreach ( $PageNumber in 1..$NumberOfPages ) {

        $ResultPageUri = $BaseUri.AbsoluteUri + "&page=$($PageNumber.ToString())"

        Try {
            $PageResponse  = Invoke-WebRequest -Uri $ResultPageUri -ErrorAction Stop
        }
        Catch {
            Throw $_.Exception.Message
        }

        # The search API limits the number of requests to 10 requests per minute and per IP address (for unauthenticated requests)
        # We might be subject to the limit on the number of requests if we run function multiple times in the last minute
        $RemainingRequestsNumber = $PageResponse.Headers.'X-RateLimit-Remaining' -as [int]
        Write-Verbose "Number of remaining API requests : $($RemainingRequestsNumber)."

        If ( $RemainingRequestsNumber -le 1 ) {
            Write-Warning "The search API limits the number of requests to 10 requests per minute"
            Write-Warning "Waiting 60 seconds before processing the remaining result pages because we have exceeded this limit."
            Start-Sleep -Seconds 60
        }
        $PageResponseContent = $PageResponse.Content | ConvertFrom-Json

        Foreach ( $PageResult in $PageResponseContent.items ) {            

            $PageResult.psobject.TypeNames.Insert(0,'PSGithubSearch.IssueOrPR')
            $PageResult
        }
    }
}

Function Find-GithubUser {
<#
.SYNOPSIS
    Searches users and/or organisations on GitHub.com based on the specified search keyword(s) and parameters.
     
.DESCRIPTION
    Uses the GitHub search API to find users or organisations on GitHub.com based on the specified search keyword(s) and parameters.
 
    This API's documentation is available here : https://developer.github.com/v3/search/
 
    NOTE : The GitHub Search API limits each search to 1,000 results and the number of requests to 10 per minute.
     
.PARAMETER Keywords
    One or more keywords to search.
 
.PARAMETER Language
    To search users who have repositories written in the specified language.
 
.PARAMETER In
    To qualify which field is searched. With this qualifier you can restrict the search to just the username (login), public email address (email) or full name (fullname).
    If not specified, the default behaviour is to search in both the username, full name and public email address..
 
.PARAMETER Type
    To restrict the search to personal accounts or organization accounts.
    By default, both are searched.
 
.PARAMETER Repos
    To filter the users or organization based on the number of repositories they have.
 
.PARAMETER Location
    To filter users or organizations based on the location indicated on their profile.
 
.PARAMETER Followers
    To filter users or organizations based on the number of followers they have.
 
.PARAMETER SortBy
    To specify on which field the results should be sorted on : number of followers, number of repositories, or when they joined GitHub.
    By default, the results are sorted by best match.
 
.EXAMPLE
    Find-GithubUser -Type user -Language 'PowerShell' -Location 'Ireland' | Where-Object { $_.Hireable }
 
    Gets information on GitHub users located in Ireland, who have at least one PowerShell repository and who have indicated on their profile that they are available for hire.
 
.NOTES
    Author : Mathieu Buisson
     
.LINK
    https://github.com/MathieuBuisson/PSGithubSearch
#>

    [CmdletBinding()]
    
    Param(
        [Parameter(Position=0)]
        [string[]]$Keywords,

        [Parameter(Position=1)]
        [string]$Language,

        [Parameter(Position=2)]
        [ValidateSet('login','email','fullname')]
        [string]$In,

        [Parameter(Position=3)]
        [ValidateSet('user','org')]
        [string]$Type,

        [Parameter(Position=4)]
        [ValidatePattern('^[\d<>][=\d]\d*$')]
        [string]$Repos,

        [Parameter(Position=5)]
        [string]$Location,

        [Parameter(Position=6)]
        [ValidatePattern('^[\d<>][=\d]\d*$')]
        [string]$Followers,

        [Parameter(Position=7)]
        [ValidateSet('followers','repositories','joined')]
        [string]$SortBy
    )

    [string]$QueryString = 'q='
    $EmptyQueryString = $True

    If ( $Keywords ) {
        $QueryString += ($Keywords -join '+')
        $EmptyQueryString = $False
    }
    If ( $Language ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'language:' + $Language
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+language:' + $Language
        }
    }
    If ( $In ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'in:' + $In
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+in:' + $In
        }
    }
    If ( $Type ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'type:' + $Type
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+type:' + $Type
        }
    }
    If ( $Repos ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'repos:' + $Repos
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+repos:' + $Repos
        }
    }
    If ( $Location ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'location:' + $Location
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+location:' + $Location
        }
    }
    If ( $Followers ) {
        If ( $EmptyQueryString ) {
            $QueryString += 'followers:' + $Followers
            $EmptyQueryString = $False
        }
        Else {
            $QueryString += '+followers:' + $Followers
        }
    }
    If ( $SortBy ) {
        $QueryString += "&sort=$SortBy"
    }

    # Using the maximum number of results per page to limit the number of requests
    $QueryString += '&per_page=100'

    $UriBuilder = New-Object System.UriBuilder -ArgumentList 'https://api.github.com'
    $UriBuilder.Path = 'search/users' -as [uri]
    $UriBuilder.Query = $QueryString

    $BaseUri = $UriBuilder.Uri
    Write-Verbose "Constructed base URI : $($BaseUri.AbsoluteUri)"

    $Response = Invoke-WebRequest -Uri $BaseUri
    If ( $Response.StatusCode -ne 200 ) {

        Write-Warning "The status code was $($Response.StatusCode) : $($Response.StatusDescription)"
    }
    $NumberOfPages = Get-NumberofPage -SearchResult $Response
    Write-Verbose "Number of pages for this search result : $($NumberOfPages)"

    Foreach ( $PageNumber in 1..$NumberOfPages ) {

        $ResultPageUri = $BaseUri.AbsoluteUri + "&page=$($PageNumber.ToString())"

        Try {
            $PageResponse  = Invoke-WebRequest -Uri $ResultPageUri -ErrorAction Stop
        }
        Catch {
            Throw $_.Exception.Message
        }

        # The search API limits the number of requests to 10 requests per minute and per IP address (for unauthenticated requests)
        # We might be subject to the limit on the number of requests if we run function multiple times in the last minute
        $RemainingRequestsNumber = $PageResponse.Headers.'X-RateLimit-Remaining' -as [int]
        Write-Verbose "Number of remaining API requests : $($RemainingRequestsNumber)."

        If ( $RemainingRequestsNumber -le 1 ) {
            Write-Warning "The search API limits the number of requests to 10 requests per minute"
            Write-Warning "Waiting 60 seconds before processing the remaining result pages because we have exceeded this limit."
            Start-Sleep -Seconds 60
        }
        $PageResponseContent = $PageResponse.Content | ConvertFrom-Json

        Foreach ( $PageResult in $PageResponseContent.items ) {
                       
            $UserDetailsResponse = Invoke-WebRequest -Uri $PageResult.url

            If ( ($UserDetailsResponse.Headers.'X-RateLimit-Remaining' -as [int]) -le 1 ) {
                Write-Warning "The search API limits the number of requests to 10 requests per minute"
                Write-Warning "Waiting 60 seconds before processing the remaining result pages because we have exceeded this limit."
                Start-Sleep -Seconds 60
            }
            $UserDetails = $UserDetailsResponse.Content | ConvertFrom-Json

            $UserProperties = [ordered]@{
                            'Full Name' = $UserDetails.name
                            'Company' = $UserDetails.company
                            'Blog' = $UserDetails.blog
                            'Location' = $UserDetails.location
                            'Email Address' = $UserDetails.email
                            'Hireable' = $UserDetails.hireable
                            'Bio' = $UserDetails.bio
                            'Repos' = $UserDetails.public_repos
                            'Gists' = $UserDetails.public_gists
                            'Followers' = $UserDetails.followers
                            'Following' = $UserDetails.following
                            'Joined' = $UserDetails.created_at
                            }

            Add-Member -InputObject $PageResult -NotePropertyMembers $UserProperties -Force

            $PageResult.psobject.TypeNames.Insert(0,'PSGithubSearch.User')
            $PageResult
        }
    }
}

Function Get-NumberofPage {
<#
.SYNOPSIS
    Helper function to get the number of pages from a search result response.
#>

    [CmdletBinding()]
    [OutputType([System.Int32])]
    Param(
        [Parameter(Mandatory=$True,Position=0)]
        [PSObject]$SearchResult
    )

    $PaginationInfo = $SearchResult.Headers.Link

    If ( -not($PaginationInfo) ) {
        $NumberOfPages = 1
    }
    Else {
        $SplitPaginationInfo = $PaginationInfo -split ', '
        $LastPage = $SplitPaginationInfo | Where-Object { $_ -like '*"last"*' }
        $NumberOfPages = (($LastPage -split '&page=')[1] -split '>')[0] -as [int]
    }
    return $NumberOfPages
}