PSGalleryExplorer.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
# This is a locally sourced Imports file for local development.
# It can be imported by the psm1 in local development to add script level variables.
# It will merged in the build process. This is for local development only.

#region scriptvariables

function Get-DataLocation {
    $folderName = "PSGalleryExplorer"
    if ($PROFILE) {
        $script:dataPath = (Join-Path (Split-Path -Parent $PROFILE) $folderName)
    }
    else {
        $script:dataPath = "~\${$folderName}"
    }
}

$script:corps = @(
    'AWS'
    'Amazon'
    'Amazon.com, Inc'
    'AtlassianPS'
    'Bentley Systems, Incorporated'
    'BitTitan'
    'BitTitan, Inc.'
    '(c) 2014 Microsoft Corporation. All rights reserved.'
    'CData Software, Inc.'
    'Chocolatey Software'
    'Cisco Systems'
    'Cisco'
    'DSC Community'
    'Dell Inc.'
    'Dell'
    'DevScope'
    'Docker Inc.'
    'Docker'
    'Google Inc'
    'Google Inc.'
    'Hewlett Packard Enterprise Co.'
    'Hewlett Packard Enterprise'
    'Hewlett-Packard Enterprise'
    'https://github.com/ebekker/ACMESharp'
    'Ironman Software, LLC'
    'JumpCloud'
    'Kelverion'
    'Kelverion Automation Limited'
    'Microsoft (Xbox)'
    'Microsoft Corp'
    'Microsoft Corporation'
    'Microsoft'
    'MosaicMK Software LLC'
    'MosaicMKSoftwareLLC'
    'Mozilla Corporation'
    'Octopus Deploy Pty. Ltd'
    'Octopus Deploy'
    'Pentia A/S'
    'Pentia'
    'PowerShell.org'
    'Pure Storage, Inc.'
    'Red Gate Software Ltd.'
    'SecureMFA'
    'SecureMFA.com'
    'SolarWinds Worldwide, LLC.'
    'SolarWinds'
    'SynEdgy Limited'
    'Synergex International Corporation'
    'VMware'
    'VMware, Inc.'
    'waldo.be'
)
$script:regulars = @(
    'BuildHelpers'
    'Carbon'
    'ImportExcel'
    'Invokebuild'
    'PendingReboot'
    'PSDepend'
    'PSDeploy'
    'PSKoans'
    'PSLogging'
    'PSSlack'
    'PSWindowsUpdate'
    'Pester'
    'PoshBot'
    'Selenium'
    'Write-ObjectToSQL'
    'dbatools'
    'oh-my-posh'
    'posh-git'
    'powershell-yaml'
    'psake'
)

$domain = 'amazonaws.com'
$prefix = 'psge-pubxml'
$target = 's3-accelerate'
Get-DataLocation
$script:dataFileZip = 'PSGalleryExplorer.zip'
$script:dataFile = 'PSGalleryExplorer.xml'
$script:dlURI = "$prefix.$target.$domain"
$script:glData = $null

#endregion

<#
.SYNOPSIS
    Confirm data output location. Creates output dir if not present.
.DESCRIPTION
    Evaluates presence of data output location for xml dataset. If the directory is not found, it will be created.
.EXAMPLE
    Confirm-DataLocation
 
    Confirms presence of data output location. Creates if not found.
.OUTPUTS
    System.Boolean
.NOTES
    None
.COMPONENT
    PSGalleryExplorer
#>

function Confirm-DataLocation {
    [CmdletBinding()]
    param (
    )
    $result = $true #assume the best
    Write-Verbose -Message 'Verifying data set output location...'
    try {
        $pathEval = Test-Path -Path $script:dataPath -ErrorAction Stop
    }#try
    catch {
        $result = $false
        Write-Error $_
        return $result
    }#catch

    if (-not ($pathEval)) {
        Write-Verbose -Message 'Creating output directory...'
        try {
            $newItemSplat = @{
                ItemType    = 'Directory'
                Path        = $script:dataPath
                ErrorAction = 'Stop'
            }
            $null = New-Item @newItemSplat
            Write-Verbose -Message 'Created.'
        }
        catch {
            $result = $false
            Write-Error $_
            return $result
        }
    }#if_TestPath
    else {
        Write-Verbose 'Data path confirmed.'
    }

    return $result
}#Confirm-DataLocation

<#
.SYNOPSIS
    Confirms the XML dataset file is available and not beyond the expiration time.
.DESCRIPTION
    Confirms the XML dataset file is present on the file system for use. Determines the age of the XML dataset file. Returns true if present and 9 days older or more.
.EXAMPLE
    Confirm-XMLDataSet
 
    Checks for XML dataset and determines if it is 9 days older or more.
.OUTPUTS
    System.Boolean
.NOTES
    Used for PSGalleryExplorer
.COMPONENT
    PSGalleryExplorer
#>

function Confirm-XMLDataSet {
    [CmdletBinding()]
    param (
    )
    $result = $true #assume the best
    $dataFile = "$script:dataPath\$script:dataFile"

    Write-Verbose -Message 'Confirming valid and current data set...'

    try {
        $pathEval = Test-Path -Path $dataFile -ErrorAction Stop
    }#try
    catch {
        $result = $false
        Write-Error $_
        return $result
    }#catch

    if (-not ($pathEval)) {
        $result = $false
    }#if_TestPath
    else {
        Write-Verbose 'Data file found. Checking date of file...'
        try {
            $fileData = Get-ChildItem -Path $dataFile -ErrorAction Stop
        }
        catch {
            $result = $false
            Write-Error $_
            return $result
        }
        if ($fileData) {
            $creationDate = $fileData.CreationTime
            $now = Get-Date
            if (($now - $creationDate).Days -ge 9) {
                Write-Verbose 'Data file requires refresh.'
                $result = $false
            }
            else {
                Write-Verbose 'Data file verified'
            }
        }
        else {
            Write-Warning 'Unable to retrieve file information for PSGalleryExplorer data set.'
            $result = $false
            return $result
        }
    }

    return $result
}#Confirm-XMLDataSet

<#
.SYNOPSIS
    Unzips the XML data set.
.DESCRIPTION
    Evalutes for previous version of XML data set and removes if required. Expands the XML data set for use.
.EXAMPLE
    Expand-XMLDataSet
 
    Unzips and expands the XML data set.
.OUTPUTS
    System.Boolean
.NOTES
    None
.COMPONENT
    PSGalleryExplorer
#>

function Expand-XMLDataSet {
    [CmdletBinding()]
    param (
    )
    $result = $true #assume the best
    Write-Verbose -Message 'Testing if data set file alread exists...'
    try {
        $pathEval = Test-Path -Path "$script:dataPath\$script:dataFile" -ErrorAction Stop
        Write-Verbose -Message "EVAL: $true"
    }#try
    catch {
        $result = $false
        Write-Error $_
        return $result
    }#catch

    if ($pathEval) {
        Write-Verbose -Message 'Removing existing data set file...'
        try {
            $removeItemSplat = @{
                Force       = $true
                Path        = "$script:dataPath\$script:dataFile"
                ErrorAction = 'Stop'
            }
            Remove-Item @removeItemSplat
        }#try
        catch {
            $result = $false
            Write-Error $_
            return $result
        }#catch
    }#if_pathEval

    Write-Verbose -Message 'Expanding data set archive...'
    try {
        $expandArchiveSplat = @{
            DestinationPath = "$script:dataPath"
            Force           = $true
            ErrorAction     = 'Stop'
            Path            = "$script:dataPath\$script:dataFileZip"
        }
        $null = Expand-Archive @expandArchiveSplat
        Write-Verbose -Message 'Expand completed.'
    }#try
    catch {
        $result = $false
        Write-Error $_
    }#catch

    return $result
}#Expand-XMLDataSet

<#
.SYNOPSIS
    Downloads XML Data set to device.
.DESCRIPTION
    Retrieves XML Data zip file from web and downloads to device.
.EXAMPLE
    Get-XMLDataSet
 
    Downloads XML data set to data path.
.OUTPUTS
    System.Boolean
.NOTES
    Overwrites existing zip file.
.COMPONENT
    PSGalleryExplorer
#>

function Get-XMLDataSet {
    [CmdletBinding()]
    param (
    )
    $result = $true #assume the best
    Write-Verbose -Message 'Downloading XML data set...'
    try {
        $invokeWebRequestSplat = @{
            OutFile     = "$script:dataPath\$script:dataFileZip"
            Uri         = "$script:dlURI/$script:dataFileZip"
            ErrorAction = 'Stop'
        }
        $oldProgressPreference = $progressPreference
        $progressPreference = 'SilentlyContinue'
        if ($PSEdition -eq 'Desktop') {
            $null = Invoke-WebRequest @invokeWebRequestSplat -PassThru -UseBasicParsing
        }
        else {
            $null = Invoke-WebRequest @invokeWebRequestSplat -PassThru
        }
    }#try
    catch {
        $result = $false
        Write-Error $_
    }#catch
    finally {
        $progressPreference = $oldProgressPreference
    }#finally
    return $result
}#Get-XMLDataSet

<#
.SYNOPSIS
    Evaluates if XML data set is in memory and kicks of child processes to obtain XML data set.
.DESCRIPTION
    XML data set will be evaluated if already in memory. If not, a series of processes will be kicked off to load the XML data set for use.
.EXAMPLE
    Import-XMLDataSet
 
    Loads the XML data set into memory.
.OUTPUTS
    System.Boolean
.NOTES
    Parent process for getting XML data.
.COMPONENT
    PSGalleryExplorer
#>

function Import-XMLDataSet {
    [CmdletBinding()]
    param (
    )
    $result = $true #assume the best
    Write-Verbose -Message 'Verifying current state of XML data set...'
    if ($null -eq $script:glData) {
        $dataCheck = Invoke-XMLDataCheck
        if ($dataCheck) {
            try {
                $getContentSplat = @{
                    Path        = "$script:dataPath\$script:dataFile"
                    Raw         = $true
                    ErrorAction = 'Stop'
                }
                $fileData = Get-Content @getContentSplat
                $script:glData = $fileData | ConvertFrom-Clixml -ErrorAction Stop
            }#try
            catch {
                $result = $false
                Write-Error $_
            }#catch
        }#if_dataCheck
        else {
            $result = $false
        }#else_dataCheck
    }#if_gldata
    return $result
}#Import-XMLDataSet

<#
.SYNOPSIS
    Invokes all child functions required to process retrieving the XML data set file.
.DESCRIPTION
    Runs all required child functions to successfull retrieve and process the XML data set file.
.EXAMPLE
    Invoke-XMLDataCheck
 
    Downloads, expands, and verified the XML data set file.
.OUTPUTS
    System.Boolean
.NOTES
    Confirm-XMLDataSet
    Get-XMLDataSet
    Expand-XMLDataSet
.COMPONENT
    PSGalleryExplorer
#>

function Invoke-XMLDataCheck {
    [CmdletBinding(ConfirmImpact = 'Low',
        SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $false,
            HelpMessage = 'Skip confirmation')]
        [switch]$Force
    )
    Begin {

        if (-not $PSBoundParameters.ContainsKey('Verbose')) {
            $VerbosePreference = $PSCmdlet.SessionState.PSVariable.GetValue('VerbosePreference')
        }
        if (-not $PSBoundParameters.ContainsKey('Confirm')) {
            $ConfirmPreference = $PSCmdlet.SessionState.PSVariable.GetValue('ConfirmPreference')
        }
        if (-not $PSBoundParameters.ContainsKey('WhatIf')) {
            $WhatIfPreference = $PSCmdlet.SessionState.PSVariable.GetValue('WhatIfPreference')
        }

        Write-Verbose -Message ('[{0}] Confirm={1} ConfirmPreference={2} WhatIf={3} WhatIfPreference={4}' -f $MyInvocation.MyCommand, $Confirm, $ConfirmPreference, $WhatIf, $WhatIfPreference)

        $results = $true #assume the best
    }#begin
    Process {
        # -Confirm --> $ConfirmPreference = 'Low'
        # ShouldProcess intercepts WhatIf* --> no need to pass it on
        if ($Force -or $PSCmdlet.ShouldProcess("ShouldProcess?")) {
            Write-Verbose -Message ('[{0}] Reached command' -f $MyInvocation.MyCommand)
            $ConfirmPreference = 'None'

            $dataOutputDir = Confirm-DataLocation
            if ($dataOutputDir -eq $true) {
                $confirm = Confirm-XMLDataSet
                if (-not $Confirm -eq $true) {
                    $retrieve = Get-XMLDataSet
                    if ($retrieve -eq $true) {
                        $expand = Expand-XMLDataSet
                        if (-not $expand -eq $true) {
                            $results = $false
                        }
                    }
                    else {
                        $results = $false
                    }
                }#if_Confirm
            }#if_dataoutput
            else {
                $results = $false
            }#else_dataoutput

        }#if_Should
    }#process
    End {
        return $results
    }#end
}#Invoke-XMLDataCheck

<#
.EXTERNALHELP PSGalleryExplorer-help.xml
#>

function Find-PSGModule {
    [CmdletBinding(defaultparametersetname = 'none')]
    param (
        [Parameter(ParameterSetName = 'GalleryDownloads',
            HelpMessage = 'Find by PowerShell Gallery Downloads')]
        [switch]
        $ByDownloads,
        [Parameter(ParameterSetName = 'Repo',
            HelpMessage = 'Find by Repository metrics')]
        [ValidateSet(
            'StarCount',
            'Forks',
            'Issues',
            'Subscribers'
        )]
        [string]
        $ByRepoInfo,
        [Parameter(ParameterSetName = 'Update',
            HelpMessage = 'Find by recently updated')]
        [string]
        [ValidateSet(
            'GalleryUpdate',
            'RepoUpdate'
        )]
        $ByRecentUpdate,
        [Parameter(ParameterSetName = 'GalleryDownloads',
            HelpMessage = 'Find random PowerShell Gallery modules')]
        [switch]
        $ByRandom,
        [Parameter(ParameterSetName = 'Names',
            HelpMessage = 'Find by name')]
        [string]
        $ByName,
        [Parameter(ParameterSetName = 'Tags',
            HelpMessage = 'Find by tag')]
        [string]
        [ValidatePattern('^[A-Za-z]+')]
        $ByTag,
        [Parameter(HelpMessage = 'Include corporation results')]
        [switch]
        $IncludeCorps,
        [Parameter(HelpMessage = 'Include more popular results')]
        [switch]
        $IncludeRegulars,
        [Parameter(Mandatory = $false,
            HelpMessage = 'Max number of modules to return')]
        [int]
        $NumberToReturn = 35
    )
    Write-Verbose -Message 'Verifying XML Data Set Availability...'
    if (Import-XMLDataSet) {
        Write-Verbose -Message 'Verified.'

        #__________________________________________________________
        Write-Verbose -Message 'Processing exclusions...'
        if ($IncludeCorps -and $IncludeRegulars) {
            $dataSet = $script:glData
        }
        elseif ($ByName) {
            $dataSet = $script:glData
        }
        elseif ($IncludeCorps) {
            $dataSet = $script:glData | Where-Object {
                $_.Name -notin $script:regulars
            }
        }
        elseif ($IncludeRegulars) {
            $dataSet = $script:glData | Where-Object {
                $_.AdditionalMetadata.CompanyName -notin $script:corps -and
                $_.Author -notin $script:corps -and
                $_.AdditionalMetadata.copyright -notin $script:corps
            }
        }
        else {
            $dataSet = $script:glData | Where-Object {
                $_.AdditionalMetadata.CompanyName -notin $script:corps -and
                $_.Author -notin $script:corps -and
                $_.AdditionalMetadata.copyright -notin $script:corps -and
                $_.Name -notin $script:regulars
            }
        }
        Write-Verbose -Message 'Exclusions completed.'
        #__________________________________________________________
        if ($ByRepoInfo) {
            Write-Verbose -Message 'ByRepoInfo'
            $gitModules = $dataSet | Where-Object { $_.GitHubInfo.GitStatus -eq $true }
            $find = $gitModules | Sort-Object -Property { [int]$_.GitHubInfo.$ByRepoInfo } -Descending | Select-Object -First $NumberToReturn
        }#if_ByRepoInfo
        elseif ($ByDownloads) {
            Write-Verbose -Message 'ByDownloads'
            $find = $dataSet | Sort-Object -Property { [int]$_.AdditionalMetadata.downloadCount } -Descending | Select-Object -First $NumberToReturn
        }#elseif_ByDownloads
        elseif ($ByRecentUpdate) {
            Write-Verbose -Message 'ByRecentUpdate'
            switch ($ByRecentUpdate) {
                'GalleryUpdate' {
                    $find = $dataSet | Sort-Object -Property { [datetime]$_.AdditionalMetadata.updated } -Descending | Select-Object -First $NumberToReturn
                }
                'RepoUpdate' {
                    $gitModules = $dataSet | Where-Object { $_.GitHubInfo.GitStatus -eq $true }
                    $find = $gitModules | Sort-Object -Property { [datetime]$_.GitHubInfo.Updated } -Descending | Select-Object -First $NumberToReturn
                }
            }
        }#elseif_ByRecentUpdate
        elseif ($ByRandom) {
            Write-Verbose -Message 'ByRandom'
            $captured = @()
            $randoms = @()
            for ($i = 0; $i -lt $NumberToReturn; $i++) {
                $thisRound = $null
                $thisRound = $dataSet | Where-Object { $captured -notcontains $_.Name } | Get-Random
                $captured += $thisRound.Name
                $randoms += $thisRound
            }
            $find = $randoms | Sort-Object -Property { [int]$_.AdditionalMetadata.downloadCount } -Descending
        }#elseif_ByRandom
        elseif ($ByName) {
            Write-Verbose -Message 'ByName'
            if ($ByName -like '*`**') {
                $find = $dataSet | Where-Object { $_.Name -like $ByName }
            }
            else {
                $find = $dataSet | Where-Object { $_.Name -eq $ByName }
            }
        }#ByName
        elseif ($ByTag) {
            Write-Verbose -Message 'ByTag'
            $tagModules = $dataSet | Where-Object { $ByTag -in $_.Tags }
            $find = $tagModules | Sort-Object -Property { [int]$_.AdditionalMetadata.downloadCount } -Descending | Select-Object -First $NumberToReturn
        }#ByTag
        else {
            $find = $dataSet | Sort-Object -Property { [int]$_.AdditionalMetadata.downloadCount } -Descending
        }#everything
        #__________________________________________________________
    }#if_Import-XMLDataSet
    else {
        Write-Warning -Message 'PSGalleryExplorer was unable to source the required data set file.'
        Write-Warning -Message 'Ensure you have an active internet connection'
        return
    }#else_Import-XMLDataSet

    Write-Verbose -Message 'Adding output properties to objects...'
    foreach ($item in $find) {
        $metrics = $null
        $metrics = @{
            Downloads  = $item.AdditionalMetadata.downloadCount
            LastUpdate = $item.AdditionalMetadata.lastUpdated
            Star       = $item.GitHubInfo.StarCount
            Sub        = $item.GitHubInfo.Subscribers
            Watch      = $item.GitHubInfo.Watchers
            Fork       = $item.GitHubInfo.Forks
            Issues     = $item.GitHubInfo.Issues
            RepoUpdate = $item.GitHubInfo.Updated
        }
        $item | Add-Member -NotePropertyMembers $metrics -TypeName Asset -Force
        $item.PSObject.TypeNames.Insert(0, 'PSGEFormat')
    }#foreach_find
    Write-Verbose -Message 'Properties addition completed.'

    return $find
}#Find-PSGModule