InstallManager.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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
#Requires -Version 5.1
###############################################################################################
# Module Variables
###############################################################################################
$ModuleVariableNames = ('IMConfiguration')
$ModuleVariableNames.ForEach( { Set-Variable -Scope Script -Name $_ -Value $null })
enum InstallManager { Chocolatey; Git; PowerShellGet; Manual }

###############################################################################################
# Module Removal
###############################################################################################
#Clean up objects that will exist in the Global Scope due to no fault of our own . . . like PSSessions

$OnRemoveScript = {
  # perform cleanup
  Write-Verbose -Message 'Removing Module Items from Global Scope'
}

$ExecutionContext.SessionState.Module.OnRemove += $OnRemoveScript

function Export-IMDefinition
{
  <#
  .SYNOPSIS
    Export one or more Install Manager Definitions to a json formatted file for import using Import-IMDefinition
  .DESCRIPTION
    Export one or more Install Manager Definitions to a json formatted file for import using Import-IMDefinition. Used for export/import scenarios between systems where the same configuration is desired.
  .EXAMPLE
    Export-IMDefinition -InstallManager Chocolatey -Path c:\local\IMChocoDefinitions.json
    Exports all Chocolatey Install Manager definitions to the specifed json file.
  .EXAMPLE
    Export-IMDefinition -Name rufus,textmate,UniversalDashboard -Path c:\local\IMDefinitions.json
    Exports Install Manager definitions for rufus, textmate, and UniversalDashboard to the specifed json file.
  .EXAMPLE
    Export-IMDefinition -Path c:\local\IMDefinitions.json
    Exports all existing Install Manager definitions to the specifed json file.
  .EXAMPLE
    Get-IMDefinition Terminal-Icons | Export-IMDefinition -Path c:\local\Terminal-Icons.json
    Exports the Install Manager definitions for the Terminal-Icons module to the specifed json file.
  .INPUTS
  .OUTPUTS
  .NOTES
  #>

  [CmdletBinding(DefaultParameterSetName = 'All')]
  param (
    #Specify the name (or names) of the Install Manager Definition(s) to export.
    [parameter(Mandatory, ParameterSetName = 'Name')]
    [string[]]$Name
    ,
    #Specify the name (or names) of the Install Manager Definition(s) to export.
    [parameter(ParameterSetName = 'Name')]
    [parameter(ParameterSetName = 'InstallManager', Mandatory)]
    [InstallManager[]]$InstallManager
    ,
    #Specify the file path for the output file. The parent container/directory must already exist. File format will be json. File will be overwritten if it exists.
    [parameter(Mandatory)]
    [Alias('Path')]
    [ValidateScript( { Test-Path -Path $(Split-Path -path $_ -Parent) -PathType Container })]
    $FilePath
    ,
    #Allows submission of an IMDefinition object via pipeline or named parameter
    [Parameter(ValueFromPipeline, ParameterSetName = 'IMDefinition')]
    [ValidateScript( { $_.psobject.TypeNames[0] -like '*IMDefinition' })]
    [psobject]$IMDefinition
  )

  begin
  {
    if ($PSCmdlet.ParameterSetName -eq 'IMDefinition')
    {
      [System.Collections.Generic.List[object]]$DefsToExport = @()
    }
  }

  process
  {
    switch ($PSCmdlet.ParameterSetName)
    {
      'All'
      {
        Export-PSFConfig -FullName "$($MyInvocation.MyCommand.ModuleName).Definitions.*" -OutPath $FilePath
      }
      'Name'
      {
        @(
          foreach ($n in $Name)
          {
            switch ($InstallManager.count)
            {
              0
              {
                Get-PSFConfig -Module $MyInvocation.MyCommand.ModuleName -Name "Definitions.*.$n"
              }
              Default
              {
                foreach ($im in $InstallManager)
                {
                  Get-PSFConfig -Module $MyInvocation.MyCommand.ModuleName -Name "Definitions.$im.$n"
                }
              }
            }
          }
        ) |
        Export-PSFConfig -OutPath $FilePath
      }
      'InstallManager'
      {
        @(
          foreach ($im in $InstallManager)
          {
            Get-PSFConfig -Module $MyInvocation.MyCommand.ModuleName -Name "Definitions.$im.*"
          }
        ) |
        Export-PSFConfig -OutPath $FilePath
      }
      'IMDefinition'
      {
        foreach ($im in $IMDefinition)
        {
          [void]$DefsToExport.add($(Get-PSFConfig -Module $MyInvocation.MyCommand.ModuleName -Name "Definitions.$($im.InstallManager).$($im.Name)"))
        }
      }
    }
  }
  end
  {
    if ($PSCmdlet.ParameterSetName -eq 'IMDefinition')
    {
      $DefsToExport | Export-PSFConfig -OutPath $FilePath
    }
  }
}

Function Get-IMChocoInstall
{
    <#
    .SYNOPSIS
        Gets an installation information object for all or specified choco packages
    .DESCRIPTION
        Gets an installation information object for all or specified choco packages
    .EXAMPLE
        PS C:\> Get-IMChocoInstall -Name docker-desktop
 
        Name : docker-desktop
        Version : 2.2.0.0
        IsLatestVersion : True
        LatestRepositoryVersion : 2.2.0.0
        LatestVersionInstalled : True
 
        Returns an object with information about the installed version of the package, if any, along with information about the latest version available in the repository.
 
    .EXAMPLE
        PS C:\> Get-IMChocoInstall
 
        Returns an object with information for each choco installed package, if any, along with information about the latest version available in the repository. Does not return any information for not installed packages.
 
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    [CmdletBinding(DefaultParameterSetName = 'All')]
    param(
        # Use to specify the name of the chocolatey package install information to return. If omitted, returns all available installation information. Accepts installed or not installed package names.
        [parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Named', Position = 1)]
        [string[]]$Name
        #,
        #[string]$Repository
        #,
        #[switch]$PerInstalledVersion
    )
    begin
    { }
    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'Named'
            {
                foreach ($n in $Name)
                {
                    $ip = $(
                        Invoke-Command -scriptblock $([scriptblock]::Create("choco list $n --LocalOnly --LimitOutput --Exact")) | ForEach-Object {
                            $packageName, $installedVersion = $_.split('|')
                            [PSCustomObject]@{
                                Name             = "$packageName"
                                InstalledVersion = $installedVersion
                            }
                        }
                    )
                    $ap = $(
                        Invoke-Command -scriptblock $([scriptblock]::Create("choco list $n --LimitOutput --Exact")) | ForEach-Object {
                            $packageName, $availableVersion = $_.split('|')
                            [PSCustomObject]@{
                                Name             = "$packageName"
                                AvailableVersion = $availableVersion
                            }
                        }
                    )
                    [PSCustomObject]@{
                        Name                    = $n
                        Version                 = $ip.InstalledVersion
                        IsLatestVersion         = $ip.InstalledVersion -eq $ap.AvailableVersion
                        #AllInstalledVersions =
                        #Repository
                        #PublishedDate
                        LatestRepositoryVersion = $ap.AvailableVersion
                        #LatestRepositoryVersionPublishedDate
                        LatestVersionInstalled  = $ip.InstalledVersion -eq $ap.AvailableVersion
                    }
                }
            }
        }
    }
    end
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'All'
            {
                $ChocoInstalledPackages = @(
                    Invoke-Command -scriptblock $([scriptblock]::Create("choco list --LocalOnly --LimitOutput")) | ForEach-Object {
                        $packageName, $installedVersion = $_.split('|')
                        [PSCustomObject]@{
                            Name             = "$packageName"
                            InstalledVersion = $installedVersion
                        }
                    }
                )
                $ChocoOutdatedPackages = @(
                    Invoke-Command -scriptblock $([scriptblock]::Create("choco outdated --LimitOutput")) | ForEach-Object {
                        $packageName, $installedVersion, $latestRepositoryVersion, $pinned = $_.split('|')
                        [PSCustomObject]@{
                            Name                    = "$packageName"
                            InstalledVersion        = $installedVersion
                            LatestRepositoryVersion = $latestRepositoryVersion
                            Pinned                  = switch ($pinned) { 'true' { $true } 'false' { $false } Default { $null } }
                        }
                    }
                )
                $ChocoOutdatedPackagesNames = @($ChocoOutdatedPackages.ForEach( { $_.Name }))
                Foreach ($cip in $ChocoInstalledPackages)
                {
                    if ($ChocoOutdatedPackagesNames -contains $cip.Name)
                    {
                        $cop = $($ChocoOutdatedPackages.Where( { $_.Name -eq $cip.Name }) | Select-Object -First 1)
                        [PSCustomObject]@{
                            Name                    = $cip.Name
                            Version                 = $cip.InstalledVersion
                            IsLatestVersion         = $false
                            #AllInstalledVersions =
                            #Repository
                            #PublishedDate
                            LatestRepositoryVersion = $cop.LatestRepositoryVersion
                            #LatestRepositoryVersionPublishedDate
                            LatestVersionInstalled  = $false
                        }
                    }
                    else
                    {
                        [PSCustomObject]@{
                            Name                    = $cip.Name
                            Version                 = $cip.InstalledVersion
                            IsLatestVersion         = $true
                            #AllInstalledVersions =
                            #Repository
                            #PublishedDate
                            LatestRepositoryVersion = $cip.InstalledVersion
                            #LatestRepositoryVersionPublishedDate
                            LatestVersionInstalled  = $true
                        }
                    }
                }
            }
        }
    }
}

Function Get-IMPowerShellGetInstall
{
    <#
.SYNOPSIS
    Gets an object with information about a Powershell Module, combining information from the module itself (if installed) and PowerShellGet.
.DESCRIPTION
    Gets an object with information about a Powershell Module, combining information from the module itself (if installed) and PowerShellGet.
.EXAMPLE
    PS C:\> Get-IMPowerShellGetInstall -Name Configuration
 
    Name : Configuration
    Version : 1.3.1
    IsLatestVersion : True
    AllInstalledVersions : {1.3.1}
    InstalledFromRepository : True
    Repository : PSGallery
    InstalledLocation : C:\Program Files\PowerShell\Modules\Configuration\1.3.1
    InstalledDate : 12/11/2019 5:31:28 PM
    PublishedDate : 7/12/2018 4:45:53 AM
    LatestRepositoryVersion : 1.3.1
    LatestRepositoryVersionPublishedDate : 7/12/2018 4:45:53 AM
    LatestVersionInstalled : True
 
    Gets an object with information about the Configuration module, a module that was installed with PowerShellGet module
.EXAMPLE
    Get-IMPowerShellGetInstall pscloudflare
 
    Name : pscloudflare
    Version : 0.0.8
    IsLatestVersion : False
    AllInstalledVersions : {0.0.5, 0.0.4, 0.0.8}
    InstalledFromRepository : False
    Repository :
    InstalledLocation : ...\GitRepos\PSModules\PSCloudflare
    InstalledDate :
    PublishedDate :
    LatestRepositoryVersion : 0.0.7
    LatestRepositoryVersionPublishedDate : 1/11/2018 7:25:53 PM
    LatestVersionInstalled :
 
    Gets an object with information about the PSCloudflare module, a module that has multiple versions installed and also has a version from a local git repository.
.EXAMPLE
 
    Get-IMPowerShellGetInstall pscloudflare -PerInstalledVersion
 
    Name : pscloudflare
    Version : 0.0.5
    IsLatestVersion : False
    AllInstalledVersions : {0.0.5, 0.0.4, 0.0.8}
    InstalledFromRepository : True
    Repository : PSGallery
    InstalledLocation : C:\Program Files\PowerShell\Modules\PSCloudFlare\0.0.5
    InstalledDate : 1/22/2020 8:04:27 PM
    PublishedDate : 12/14/2017 4:00:44 AM
    LatestRepositoryVersion : 0.0.7
    LatestRepositoryVersionPublishedDate : 1/11/2018 7:25:53 PM
    LatestVersionInstalled : False
 
    Name : pscloudflare
    Version : 0.0.4
    IsLatestVersion : False
    AllInstalledVersions : {0.0.5, 0.0.4, 0.0.8}
    InstalledFromRepository : True
    Repository : PSGallery
    InstalledLocation : C:\Program Files\PowerShell\Modules\PSCloudFlare\0.0.4
    InstalledDate : 1/22/2020 8:04:24 PM
    PublishedDate : 12/22/2016 6:02:37 PM
    LatestRepositoryVersion : 0.0.7
    LatestRepositoryVersionPublishedDate : 1/11/2018 7:25:53 PM
    LatestVersionInstalled : False
 
    Name : pscloudflare
    Version : 0.0.8
    IsLatestVersion : False
    AllInstalledVersions : {0.0.5, 0.0.4, 0.0.8}
    InstalledFromRepository : False
    Repository :
    InstalledLocation : C:\Users\MikeCampbell\GitRepos\PSModules\PSCloudflare
    InstalledDate :
    PublishedDate :
    LatestRepositoryVersion : 0.0.7
    LatestRepositoryVersionPublishedDate : 1/11/2018 7:25:53 PM
    LatestVersionInstalled :
 
    Gets an object with information about each installed version the PSCloudFlare module, a module that has multiple versions installed and also has a version from a local git repository.
.INPUTS
    Inputs (if any)
.OUTPUTS
    Output (if any)
.NOTES
    General notes
#>

    [CmdletBinding(DefaultParameterSetName = 'All')]
    param(
        # Use to specify the name of one or more modules for which to get installation information
        [parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Named', Position = 1)]
        [string[]]$Name
        ,
        # use to specify an alternative repository. The repository should already be registered on the system.
        [string]$Repository
        ,
        # use to get an object per installed version of the specified module(s)
        [switch]$PerInstalledVersion
    )
    begin
    {
        [System.Collections.ArrayList]$LocalModules = @()
        [System.Collections.ArrayList]$LocalPowerShellGetModules = @()
        [System.Collections.ArrayList]$LatestRepositoryModules = @()
        [System.Collections.ArrayList]$NamedModules = @()
        [System.Collections.ArrayList]$RepoFoundModules = @()
        $FindModuleParams = @{
            ErrorAction = 'SilentlyContinue'
        }
        if ($PSBoundParameters.ContainsKey('Repository'))
        {
            $FindModuleParams.Repository = $PSBoundParameters.Repository
        }
        $GetInstalledModuleParams = @{
            ErrorAction = 'SilentlyContinue'
        }
    }
    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'All'
            {
                #Get the locally available modules on this system for the current user based on entries in $env:Psmodulepath
                $null = @(Get-Module -ListAvailable).foreach( { $LocalModules.add($_) })
                #Get the locally available modules that were installed using PowerShellGet Module commands
                $null = $LocalModules.where( { $null -ne $_.RepositorySourceLocation }).foreach( { Get-InstalledModule -Name $_.Name -RequiredVersion $_.Version @GetInstalledModuleParams }).foreach( { $LocalPowerShellGetModules.add($_) })
                $null = ($LocalModules.ForEach( { $_.Name }) | Sort-Object -Unique).foreach( { $NamedModules.add([pscustomobject]@{Name = $_ }) })
                $LocalPowerShellGetModules.ForEach( {
                        if (-not $RepoFoundModules.Contains($_.name))
                        {
                            $FindModuleParams.Name = $_.name
                            $RepositoryModule = Find-Module @FindModuleParams
                            $null = $LatestRepositoryModules.add($RepositoryModule)
                            $null = $RepoFoundModules.add($_.name)
                        }
                    })
            }
            'Named'
            {
                foreach ($n in $Name)
                {
                    #Get the locally available named module(s) on this system for the current user based on entries in $env:Psmodulepath
                    $null = $LocalModules.add($(Get-Module -ListAvailable -Name $n -ErrorAction Stop))
                    #Get the locally available named module(s) that were installed using PowerShellGet Module commands
                    $GetInstalledModuleParams.Name = $n
                    $GetInstalledModuleParams.AllVersions = $true
                    $null = $LocalPowerShellGetModules.add($(Get-InstalledModule @GetInstalledModuleParams))
                    #Get the PSGallery Module for the named module
                    $FindModuleParams.Name = $n
                    $LatestRepositoryModule = Find-Module @FindModuleParams
                    $null = $LatestRepositoryModules.add($LatestRepositoryModule)
                    $null = $NamedModules.add($([pscustomobject]@{Name = $n }))
                }
            }
        }
    }
    End
    {
        $LocalModulesLookupNV = @{ }
        $LocalModules.foreach( { $_ }) | Select-Object -Property Name, Version, Path, GUID, ModuleBase, LicenseUri, ProjectUri, @{n = 'NameVersion'; e = { [string]$($_.Name + $_.Version) } } | ForEach-Object -Process { $LocalModulesLookupNV.$($_.NameVersion) = $_ }
        #$LocalModulesLookupN = $LocalModules.foreach({$_}) | Select-Object -Property Name,Version,Path,GUID,ModuleBase,LicenseUri,ProjectUri,@{n='NameVersion';e={$_.Name + $_.Version}} | Group-Object -AsHashTable -Property Name
        $LocalPowerShellGetModulesLookup = @{ }
        $LocalPowerShellGetModules.foreach( { $_ }) | Select-Object -Property Name, Version, Author, PublishedDate, InstalledDate, UpdatedDate, LicenseUri, InstalledLocation, Repository, @{n = 'NameVersion'; e = { $_.Name + $_.Version } } | ForEach-Object -Process { $LocalPowerShellGetModulesLookup.$($_.NameVersion) = $_ }
        $LatestRepositoryModulesLookup = @{ }
        $LatestRepositoryModules.foreach( { $_ }) | Select-Object -Property Name, Version, Author, PublishedDate, LicenseUri, ProjectUri, Repository | ForEach-Object -Process { $LatestRepositoryModulesLookup.$($_.Name) = $_ }
        switch ($PSCmdlet.ParameterSetName)
        {
            'All'
            {
                $PerInstalledVersionOutput = @(
                    foreach ($lm in $LocalModules.foreach( { $_ }))
                    {
                        $lookup = $lm.Name + $lm.Version
                        [PSCustomObject]@{
                            Name                                 = $lm.Name
                            Version                              = $lm.Version
                            IsLatestVersion                      = if ($null -ne $LatestRepositoryModulesLookup.$($lm.name).Version) { $lm.version -eq $LatestRepositoryModulesLookup.$($lm.name).Version } else { $null }
                            AllInstalledVersions                 = @($LocalModules.foreach( { $_ }).where( { $_.Name -ieq $lm.Name }).foreach( { $_.Version.tostring() }))
                            InstalledFromRepository              = $null -ne $lm.RepositorySourceLocation
                            Repository                           = $LocalPowerShellGetModulesLookup.$lookup.Repository
                            InstalledLocation                    = $lm.ModuleBase
                            InstalledDate                        = $LocalPowerShellGetModulesLookup.$lookup.InstalledDate
                            PublishedDate                        = $LocalPowerShellGetModulesLookup.$lookup.PublishedDate
                            LatestRepositoryVersion              = $LatestRepositoryModulesLookup.$($lm.name).Version
                            LatestRepositoryVersionPublishedDate = $LatestRepositoryModulesLookup.$($lm.name).PublishedDate
                            LatestVersionInstalled               = if ($null -eq $lm.RepositorySourceLocation) { $null } else { $LocalModulesLookupNV.ContainsKey($lm.Name + $LatestRepositoryModulesLookup.$($lm.name).Version.tostring()) }
                        }
                    }
                )
            }
            'Named'
            {
                $PerInstalledVersionOutput = @(
                    foreach ($nm in $NamedModules)
                    {
                        if ($LocalModules.foreach( { $_ }).where( { $_.Name -ieq $nm.Name }).count -ge 1)
                        {
                            foreach ($lm in $LocalModules.foreach( { $_ }).where( { $_.Name -ieq $nm.Name }))
                            {
                                $lookup = $nm.Name + $lm.Version
                                [PSCustomObject]@{
                                    Name                                 = $nm.Name
                                    Version                              = $lm.Version
                                    IsLatestVersion                      = if ($null -ne $LatestRepositoryModulesLookup.$($nm.name).Version) { $lm.version -eq $LatestRepositoryModulesLookup.$($nm.name).Version } else { $null }
                                    AllInstalledVersions                 = @($LocalModules.foreach( { $_ }).where( { $_.Name -ieq $nm.Name }).foreach( { $_.Version }))
                                    InstalledFromRepository              = $null -ne $lm.RepositorySourceLocation
                                    Repository                           = $LocalPowerShellGetModulesLookup.$lookup.Repository
                                    InstalledLocation                    = $lm.ModuleBase
                                    InstalledDate                        = $LocalPowerShellGetModulesLookup.$lookup.InstalledDate
                                    PublishedDate                        = $LocalPowerShellGetModulesLookup.$lookup.PublishedDate
                                    LatestRepositoryVersion              = $LatestRepositoryModulesLookup.$($nm.name).Version
                                    LatestRepositoryVersionPublishedDate = $LatestRepositoryModulesLookup.$($nm.name).PublishedDate
                                    LatestVersionInstalled               = if ($null -eq $lm.RepositorySourceLocation) { $null } else { $LocalModulesLookupNV.ContainsKey($lm.Name + $LatestRepositoryModulesLookup.$($lm.name).Version.tostring()) }
                                    #LatestVersionInstalled = $LocalModulesLookupNV.ContainsKey($nm.Name + $LatestRepositoryModulesLookup.$($nm.name).Version.tostring())
                                }
                            }
                        }
                        else
                        {
                            $lookup = $nm.Name
                            [PSCustomObject]@{
                                Name                                 = $lookup
                                Version                              = $null
                                IsLatestVersion                      = $null
                                AllInstalledVersions                 = $null
                                InstalledFromRepository              = $null
                                Repository                           = $LatestRepositoryModulesLookup.$lookup.Repository
                                InstalledLocation                    = $null
                                InstalledDate                        = $null
                                PublishedDate                        = $null
                                LatestRepositoryVersion              = $LatestRepositoryModulesLookup.$lookup.Version
                                LatestRepositoryVersionPublishedDate = $LatestRepositoryModulesLookup.$lookup.PublishedDate
                                LatestVersionInstalled               = $false
                            }
                        }
                    }
                )
            }
        }
        switch ($PerInstalledVersion)
        {
            $true
            {
                $PerInstalledVersionOutput
            }
            $false
            {
                $PerModuleGroups = $PerInstalledVersionOutput | Group-Object -Property Name
                foreach ($pmg in $PerModuleGroups)
                {
                    $lvInstalled = $pmg.Group.Version.foreach( { $_.tostring() }) | Sort-Object -Descending | Select-Object -first 1
                    switch ($null -eq $lvInstalled)
                    {
                        $false
                        {
                            [PSCustomObject]@{
                                Name                                 = $pmg.Name
                                Version                              = $lvInstalled
                                IsLatestVersion                      = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).IsLatestVersion | Select-Object -Unique
                                AllInstalledVersions                 = @($pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).AllInstalledVersions | Select-Object -Unique)
                                InstalledFromRepository              = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).InstalledFromRepository | Select-Object -Unique
                                Repository                           = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).Repository | Select-Object -Unique
                                InstalledLocation                    = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).InstalledLocation
                                InstalledDate                        = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).InstalledDate | Select-Object -Unique
                                PublishedDate                        = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).PublishedDate | Select-Object -Unique
                                LatestRepositoryVersion              = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).LatestRepositoryVersion | Select-Object -Unique
                                LatestRepositoryVersionPublishedDate = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).LatestRepositoryVersionPublishedDate | Select-Object -Unique
                                LatestVersionInstalled               = $pmg.Group.where( { $_.version.tostring() -eq $lvInstalled }).LatestVersionInstalled | Select-Object -Unique
                            }
                        }
                        $true
                        {
                            [PSCustomObject]@{
                                Name                                 = $pmg.Name
                                Version                              = $null
                                IsLatestVersion                      = $null
                                AllInstalledVersions                 = $null
                                InstalledFromRepository              = $null
                                Repository                           = $LatestRepositoryModulesLookup.$($pmg.Name).Repository
                                InstalledLocation                    = $null
                                InstalledDate                        = $null
                                PublishedDate                        = $null
                                LatestRepositoryVersion              = $LatestRepositoryModulesLookup.$($pmg.Name).Version
                                LatestRepositoryVersionPublishedDate = $LatestRepositoryModulesLookup.$($pmg.Name).PublishedDate
                                LatestVersionInstalled               = $False
                            }
                        }
                    }
                }
            }
        }
    }
}

Function Get-IMSystemUninstallEntry
{
    <#
.SYNOPSIS
    Gets all uninstall entries from the windows registry
.DESCRIPTION
    Gets all uninstall entries from the windows registry
.EXAMPLE
    PS C:\> Get-IMSystemUninstallEntry
    Gets a powershell object with a specified set of properties for each uninstall entry found in the windows registry. Change the set of properties with the SpecifiedProperties parameter.
.EXAMPLE
    PS C:\> Get-IMSystemUninstallEntry -raw
    Gets a powershell object with all available properties for each uninstall entry found in the windows registry
.INPUTS
    Inputs (if any)
.OUTPUTS
    Output (if any)
.NOTES
    General notes
#>

    [cmdletbinding(DefaultParameterSetName = 'SpecifiedProperties')]
    param(
        # Use to return all available properties for each uninstall entry
        [parameter(ParameterSetName = 'Raw')]
        [switch]$Raw
        ,
        # Use to override the default set of properties included with the uninstall entry output objects
        [parameter(ParameterSetName = 'SpecifiedProperties')]
        [string[]]$Property = @('DisplayName', 'DisplayVersion', 'InstallDate', 'Publisher')
    )
    # paths: x86 and x64 registry keys are different
    if ([IntPtr]::Size -eq 4)
    {
        $path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
    }
    else
    {
        $path = @(
            'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'
            'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
        )
    }
    $UninstallEntries = Get-ItemProperty $path
    # use only with name and unistall information
    #.{process{ if ($_.DisplayName -and $_.UninstallString) { $_ } }} |
    # select more or less common subset of properties
    #Select-Object DisplayName, Publisher, InstallDate, DisplayVersion, HelpLink, UninstallString |
    # and finally sort by name
    #Sort-Object DisplayName
    if ($Raw) { $UninstallEntries | Sort-Object -Property DisplayName }
    else
    {
        $UninstallEntries | Sort-Object -Property DisplayName | Select-Object -Property $Property
    }

}

Function Get-IMDefinition
{
    <#
    .SYNOPSIS
        Gets the Install Manager Definitions. If no definitions have been imported yet, returns nothing. Use Import-IMDefinition to import Install Manager Definitions.
    .DESCRIPTION
        Gets the Install Manager Definitions. If no definitions have been imported yet, returns nothing. Use Import-IMDefinition to import Install Manager Definitions.
    .EXAMPLE
        Get-IMDefinition -Name Terminal-Icons
 
        Name : Terminal-Icons
        InstallManager : PowerShellGet
        RequiredVersion :
        AutoUpgrade : True
        AutoRemove : True
        ExemptMachine :
        Parameter :
        Repository : PSGallery
 
        Gets the InstallManager definition for the Terminal-Icons PowerShell Module
    .EXAMPLE
        Get-IMDefinition -InstallManager PowerShellGet
 
        Name : Terminal-Icons
        InstallManager : PowerShellGet
        RequiredVersion : 0.0.4;0.0.5
        AutoUpgrade : True
        AutoRemove : True
        ExemptMachine :
        Parameter :
        Repository : PSGallery
 
        Gets the InstallManager definitions for all definitions where InstallManager is PowerShellGet
 
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>


    [cmdletbinding(DefaultParameterSetName = 'All')]
    param(
        # Use to specify the name of the InstallManager Definition(s) to get. Accepts Wildcard.
        [parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Name', Position = 1)]
        [string[]]$Name
        ,
        # Use to specify the Install Manager for the Definition(s) to get. Used primarily for filtering in bulk operations or when multiple
        [parameter(ValueFromPipelineByPropertyName, Position = 2)]
        [InstallManager[]]$InstallManager
    )

    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'Name'
            {
                foreach ($n in $Name)
                {
                    switch ($InstallManager.count)
                    {
                        0
                        {
                            (Get-PSFConfig -Module InstallManager -Name Definitions.*.$($n)).foreach( { Get-PSFConfigValue -FullName $_.FullName })
                        }
                        Default
                        {
                            foreach ($im in $InstallManager)
                            {
                                (Get-PSFConfig -Module InstallManager -Name Definitions.$($im).$($n)).foreach( { Get-PSFConfigValue -FullName $_.FullName })
                            }
                        }
                    }
                }
            }
            'All'
            {
                switch ($InstallManager.count)
                {
                    0
                    {
                        (Get-PSFConfig -Module InstallManager -Name Definitions.*).foreach( { Get-PSFConfigValue -FullName $_.FullName })
                    }
                    Default
                    {
                        foreach ($im in $InstallManager)
                        {
                            (Get-PSFConfig -Module InstallManager -Name Definitions.$($im).*).foreach( { Get-PSFConfigValue -FullName $_.FullName })
                        }
                    }
                }
            }
        }
    }
}

Function Import-IMDefinition
{
    <#
.SYNOPSIS
    Imports definitions from a file produced by Export-IMDefition. WARNING: Overwrites any existing definition with the same name and InstallManager as an imported definition.
.DESCRIPTION
    Imports definitions from a file produced by Export-IMDefition. WARNING: Overwrites any existing definition with the same name and InstallManager as an imported definition.
.EXAMPLE
    Import-IMDefinition -FilePath c:\LocalOnly\cdefinitions.json
    Imports all the definitions in the specified file.
.INPUTS
.OUTPUTS
.NOTES
#>

    [cmdletbinding()]
    param
    (
        #Specify the file to Import, should be json format, exported with Export-IMDefinition.
        [Parameter(Mandatory)]
        [ValidateScript( { Test-Path -PathType Leaf -Path $_ })]
        $FilePath
        ,
        #If specified, only Definitions with names that are similar (-like) to names in this list will be imported.
        [parameter()]
        [string[]]$IncludeFilter
        ,
        #Definitions that are similar (-like) to names in this list will NOT be imported.
        [parameter()]
        [string[]]$ExcludeFilter
    )

    #$RequiredProperties = @('Name', 'InstallManager', 'RequiredVersion', 'AutoUpgrade', 'AutoRemove', 'ExemptMachine', 'Parameter', 'Repository', 'Scope')
    #Write-Information -MessageData "The required properties for IMDefinition(s) are: $($RequiredProperties -join ',')"
    $impConfigParams = @{
        AllowDelete = $true
        Path = $FilePath
        PassThru = $true
    }
    if ($IncludeFilter.count -ge 1)
    {
        $impConfigParams.IncludeFilter = $IncludeFilter
    }
    if ($ExcludeFilter.count -ge 1)
    {
        $impConfigParams.ExcludeFilter = $ExcludeFilter
    }

    Import-PSFConfig @impConfigParams |
    Register-PSFConfig

}

function Import-IMConfiguration
{
    $script:IMConfiguration = Get-PSFConfigValue -FullName "$($MyInvocation.MyCommand.ModuleName).Preferences"
}

function Update-IMInstall
{
    <#
    .SYNOPSIS
        Processes an IMDefinition to install, update, or remove (future) the associated package, module, or repo (future)
    .DESCRIPTION
        Processes an IMDefinition to install, update, or remove (future) the associated package, module, or repo (future)
    .EXAMPLE
        Set-IMDefinition -Name rufus -InstallManager Chocolatey
        Get-IMDefinition -Name rufus | Update-IMinstall
        processes the newly created IMDefinition for the rufus package and installs or updates the package as appropriate
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'IMDefinition')]
    param (
        #Allows submission of an IMDefinition object via pipeline or named parameter
        [Parameter(ValueFromPipeline, ParameterSetName = 'IMDefinition')]
        [ValidateScript( { $_.psobject.TypeNames[0] -like '*IMDefinition' })]
        [psobject]$IMDefinition
        ,
        # Specify the Name of the Module or Package for which to update the Install
        [Parameter(Mandatory, Position = 1, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')]
        [string[]]$Name
        ,
        # Specify the name of the Install Manager for the Definition to Install - usually only necessary in the rare case where you have a name that exists in more then one Install Manager.
        [Parameter(Position = 2, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')]
        [InstallManager]
        $InstallManager
    )

    begin
    {
        $localmachinename = [System.Environment]::MachineName
    }

    process
    {
        switch ($PSCmdlet.ParameterSetName)
        {
            'IMDefinition'
            { }

            'Name'
            {
                $IMDefinition = @(Get-IMDefinition -Name $Name -InstallManager $InstallManager)
            }
        }
        foreach ($imd in $IMDefinition)
        {
            $InstallManager = $imd.InstallManager
            $Name = $imd.Name
            $RequiredVersion = @($imd.RequiredVersion)
            $AutoUpgrade = $imd.AutoUpgrade
            $AutoRemove = $imd.AutoRemove
            $ExemptMachine = $imd.ExemptMachine
            $Parameter = $imd.Parameter
            $Scope = $imd.Scope
            if ($localmachinename -notin $ExemptMachine)
            {

                Write-Information -MessageData "Using $InstallManager to Process Install Definition: $Name"
                switch ($InstallManager)
                {
                    'PowerShellGet'
                    {
                        $installedModuleInfo = Get-IMPowerShellGetInstall -Name $Name
                        $installModuleParams = @{
                            Name          = $Name
                            Scope         = switch ([string]::IsNullOrWhiteSpace($Scope)) { $true { 'CurrentUser' } $false { $Scope } }
                            Force         = $true
                            AcceptLicense = $true
                            AllowClobber  = $true
                        }
                        if ($Parameter.count -ge 1)
                        {
                            foreach ($key in $Parameter.keys)
                            {
                                $installModuleParams.$key = $Parameter.$key
                            }
                        }
                        switch ($true -eq $AutoUpgrade)
                        {
                            $true
                            {
                                if ($false -eq $installedModuleInfo.IsLatestVersion -or $null -eq $installedModuleInfo.IsLatestVersion)
                                {
                                    if ($PSCmdlet.ShouldProcess("Install-Module " + $($installModuleParams.GetEnumerator().foreach( { '-' + $_.Name + ' ' + $_.Value }) -join ' ')))
                                    {
                                        Install-Module @installModuleParams
                                    }
                                }
                            }
                            $false
                            {
                                #notification/logging that a new version is available
                            }
                        }
                        if (-not [string]::IsNullOrEmpty($RequiredVersion))
                        {
                            $installedModuleInfo = Get-IMPowerShellGetInstall -Name $Name
                            foreach ($rv in $RequiredVersion)
                            {
                                if ($rv -notin $installedModuleInfo.AllInstalledVersions)
                                {
                                    $installModuleParams.RequiredVersion = $rv
                                    if ($PSCmdlet.ShouldProcess("Install-Module " + $($installModuleParams.GetEnumerator().foreach( { '-' + $_.Name + ' ' + $_.Value }) -join ' ')))
                                    {
                                        Install-Module @installModuleParams
                                    }
                                }
                            }
                        }
                        if ($true -eq $AutoRemove)
                        {
                            $installedModuleInfo = Get-IMPowerShellGetInstall -Name $Name
                            [System.Collections.ArrayList]$keepVersions = @()
                            $null = $RequiredVersion.ForEach( { $keepVersions.add($_) })
                            if ($true -eq $autoupgrade)
                            {
                                $null = $keepVersions.add($installedModuleInfo.LatestRepositoryVersion)
                            }
                            $removeVersions = @($installedModuleInfo.AllInstalledVersions | Where-Object -FilterScript { $_ -notin $keepVersions })
                            if ($removeVersions.Count -ge 1)
                            {
                                $UninstallModuleParams = @{
                                    Name  = $Name
                                    Force = $true
                                }
                            }
                            foreach ($rV in $removeVersions)
                            {
                                $UninstallModuleParams.RequiredVersion = $rV
                                if ($PSCmdlet.ShouldProcess("Uninstall-Module " + $($uninstallModuleParams.GetEnumerator().foreach( { '-' + $_.Name + ' ' + $_.Value }) -join ' ')))
                                {
                                    Uninstall-Module @UninstallModuleParams
                                }
                            }
                        }
                    }
                    'chocolatey'
                    {
                        $installedModuleInfo = Get-IMChocoInstall -Name $Name
                        $options = ''
                        if ($Parameter.count -ge 1)
                        {
                            foreach ($key in $Parameter.keys)
                            {
                                $options += "--$key"
                                if (-not [string]::IsNullOrWhiteSpace($Parameter.$key))
                                {
                                    $options += "=`"'$Parameter.$key'`" "
                                }
                                else
                                {
                                    $options += ' '
                                }
                            }
                        }
                        switch ($true -eq $AutoUpgrade)
                        {
                            $true
                            {
                                if ($false -eq $installedModuleInfo.IsLatestVersion -or $null -eq $installedModuleInfo.IsLatestVersion)
                                {
                                    Write-Information -MessageData "Running Command: 'choco upgrade $Name --Yes --LimitOutput $options'"
                                    if ($PSCmdlet.ShouldProcess("choco upgrade $Name --Yes --LimitOutput $options"))
                                    {
                                        Invoke-Command -ScriptBlock $([scriptblock]::Create("choco upgrade $Name --Yes --LimitOutput $options"))
                                    }
                                }
                            }
                            $false
                            {
                                if ($null -eq $installedModuleInfo)
                                {
                                    Write-Information -MessageData "Running Command: 'choco upgrade $Name --Yes --LimitOutput $options'"
                                    if ($PSCmdlet.ShouldProcess("choco upgrade $Name --Yes --LimitOutput $options"))
                                    {
                                        Invoke-Command -ScriptBlock $([scriptblock]::Create("choco upgrade $Name --Yes --LimitOutput $options"))
                                    }
                                }
                                #notification/logging that a new version is available
                            }
                        }
                    }
                }
            }
            else
            {
                Write-Information -MessageData "$localmachinename is present in ExemptMachines for Install Definition $Name"
            }
        }
    }
    end
    { }
}

function New-IMDefinition
{
  <#
  .SYNOPSIS
    Creates a new Install Manager Definition and stores it in the current user's configuration
  .DESCRIPTION
    Creates a new Install Manager Definition and stores it in the current user's configuration
  .EXAMPLE
    PS C:\> New-IMDefinition -Name sumatrapdf.install -InstallManager Chocolatey
    Adds an Install Manager Definition for the sumatrapdf.install Chocolatey package and sets it to the defaults for Chocolatey
  .INPUTS
    None
  .OUTPUTS
    None
  .NOTES
 
  #>

  [CmdletBinding(SupportsShouldProcess)]
  param (
    # Specify the Name of the Module or Package
    [Parameter(Mandatory, Position = 1)]
    [String]
    $Name
    ,
    # Specify the name of the Install Manager to use for the Module (PowerShellGet) or Package (Chocolatey)
    [Parameter(Mandatory, Position = 2)]
    [InstallManager]
    $InstallManager
    ,
    # Use to Specify one or more required versions for PowerShell Modules or a single version to pin for choco packages
    [parameter(Position = 3)]
    [string[]]$RequiredVersion
    ,
    # Use to specify that InstallManager should automatically install newer versions when update-IMInstall is used with this definition
    [parameter(Position = 4)]
    [bool]$AutoUpgrade = $true
    ,
    # Use to specify that InstallManager should automatically remove older versions when update-IMInstall installs a new version for this definition (for PowerShellGet modules, RequiredVersions are kept)
    [parameter(Position = 5)]
    [bool]$AutoRemove = $true
    ,
    # Use to specify a hashtable of additional parameters required by the Install Manager (PowerShellGet or Chocolatey) when processing this definition. Do NOT Include the leading '-' or '--' when specifying parameter names. For Chocolatey options that require no value, use $null. For PowerShellGet params such as bool or switch, use $true or $false as the value.
    [parameter(Position = 6)]
    [hashtable]$Parameter
    ,
    # Use to specify machines (by machinename/hostname) that should not process this Install Manager definition
    [parameter(Position = 7)]
    [string[]]$ExemptMachine
    ,
    # Use to Specify the name of the Repository to use for the Definition - like PSGallery, or chocolatey, or chocolatey.licensed
    [parameter(Position = 8)]
    [ValidateNotNullOrEmpty()]
    [string]$Repository
    ,
    # Use to specify the Scope for a PowerShellGet Module
    [parameter(Position = 9)]
    [ValidateSet('AllUsers', 'CurrentUser')]
    [string]$Scope
  )

  begin
  {

  }
  process
  {
    if ((Get-IMDefinition -Name $Name -InstallManager $InstallManager).count -eq 0)
    {
      $Definition =
      [pscustomobject]@{
        PSTypeName      = 'IMDefinition'
        Name            = $Name
        InstallManager  = $InstallManager -as [String] #avoid an enum serialization warning from Configuration module
        Repository      = if ([string]::IsNullOrWhiteSpace($repository))
        {
          switch ($InstallManager)
          {
            #'Chocolatey' { '' }
            'PowerShellGet' { 'PSGallery' }
            Default { '' }
          }
        }
        else { $Repository }
        RequiredVersion = switch ($PSBoundParameters.ContainsKey('RequiredVersion')) { $true { $RequiredVersion } $false { @() } }
        AutoUpgrade     = $AutoUpgrade
        AutoRemove      = $AutoRemove
        Parameter       = switch ($PSBoundParameters.ContainsKey('Parameter')) { $true { $Parameter } $false { @{ } } }
        ExemptMachine   = switch ($PSBoundParameters.ContainsKey('ExemptMachine')) { $true { $ExemptMachine } $false { @() } }
        Scope           = $Scope
      }
      if ($PSCmdlet.ShouldProcess("$Definition"))
      {
        $SetConfigParams = @{
          Module      = $MyInvocation.MyCommand.ModuleName
          AllowDelete = $true
          Passthru    = $true
          Name        = "Definitions.$Installmanager.$Name"
          Value       = $Definition
        }
        Set-PSFConfig @SetConfigParams | Register-PSFConfig
      }
    }
    else
    {
      throw("Definition for $Name with $InstallManager as the InstallManager already exists. To modify it, use Set-IMDefinition")
    }
  }

  end
  {

  }
}

function Remove-IMDefinition
{
  <#
  .SYNOPSIS
    Removes an Install Manager Definition and updates the current user's configuration
  .DESCRIPTION
    Removes an Install Manager Definition and updates the current user's configuration
  .EXAMPLE
    PS C:\> Remove-IMDefinition -Name textpad -InstallManager Chocolatey
    Removes the Install Manager Definition for the textpad Chocolatey package
  .INPUTS
    None
  .OUTPUTS
    None
  .NOTES
 
  #>

  [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Name')]
  param (
    # Specify the Name of the Module or Package
    [Parameter(Mandatory, Position = 1, ParameterSetName = 'Name')]
    [String]
    $Name
    ,
    # Specify the name of the Install Manager to use for the Module (PowerShellGet) or Package (Chocolatey)
    [Parameter(Position = 2, ParameterSetName = 'Name')]
    [InstallManager]
    $InstallManager
    ,
    # Allows submission of an IMDefinition object via pipeline or named parameter
    [Parameter(ValueFromPipeline, ParameterSetName = 'IMDefinition')]
    [ValidateScript( { $_.psobject.TypeNames[0] -like '*IMDefinition' })]
    $IMDefinition
  )

  begin
  {

  }
  process
  {
    switch ($PSCmdlet.ParameterSetName)
    {
      'Name'
      {
        $IMDefinition = @(Get-IMDefinition -Name $Name -InstallManager $InstallManager)
        switch ($IMDefinition.count)
        {
          0
          {
            Write-Warning -Message "Not Found: InstallManager Definition for $Name"
            Return
          }
          1
          {
            #All OK - found just one Definition to Remove
          }
          Default
          {
            throw("Ambiguous: InstallManager Definition for $Name. Try being more specific by specifying the InstallManager.")
          }
        }
      }
    }
    foreach ($imd in $IMDefinition)
    {
      $remConfigParams = @{
        Module = $MyInvocation.MyCommand.ModuleName
        Name   = "Definitions.$($imd.InstallManager).$($imd.Name)"
      }
      if ($PSCmdlet.ShouldProcess("Name = $($imd.Name); InstallManager = $($imd.InstallManager)"))
      {
        Set-PSFConfig @remConfigParams -AllowDelete
        $remConfigParams.Confirm = $false
        Remove-PSFConfig @remConfigParams
      }
    }
  }

  end
  {

  }
}

function Set-IMDefinition
{
  <#
  .SYNOPSIS
    Sets an InstallManager Definition and updates the current user's configuration
  .DESCRIPTION
    Sets an InstallManager Definition and updates the current user's configuration
  .EXAMPLE
    PS C:\> Set-IMDefinition -Name textpad -RequiredVersion 8.1.2
    Sets the InstallManager Definition for textpad to require version 8.1.2
  .INPUTS
    None
  .OUTPUTS
    None
  .NOTES
 
  #>

  [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Name')]
  param (
    # Specify the Name of the Module or Package for which to set the IMDefintion
    [Parameter(Mandatory, Position = 1, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')]
    [String]
    $Name
    ,
    # Specify the name of the Install Manager for the Definition to set - usually only necessary in the rare case where you have a name that exists in more then one Install Manager.
    [Parameter(Position = 2, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')]
    [InstallManager]
    $InstallManager
    ,
    #Allows submission of an IMDefinition object via pipeline or named parameter
    [Parameter(ValueFromPipeline, ParameterSetName = 'IMDefinition')]
    [ValidateScript( { $_.psobject.TypeNames[0] -like '*IMDefinition' })]
    [psobject]$IMDefinition
    ,
    # Use to Specify one or more required versions for PowerShell Modules or a single version to pin for choco packages
    [parameter(Position = 3)]
    [string[]]$RequiredVersion
    ,
    # Use to specify that InstallManager should automatically install newer versions when update-IMInstall is used with this definition
    [parameter(Position = 4)]
    [bool]$AutoUpgrade
    ,
    # Use to specify that InstallManager should automatically remove older versions when update-IMInstall installs a new version for this definition (for PowerShellGet modules, RequiredVersions are kept)
    [parameter(Position = 5)]
    [bool]$AutoRemove
    ,
    # Use to specify a hashtable of additional parameters required by the Install Manager (PowerShellGet or Chocolatey) when processing this definition. Do NOT Include the leading '-' or '--' when specifying parameter names.
    [parameter(Position = 6)]
    [hashtable]$Parameter
    ,
    # Use to specify machines (by machinename/hostname) that should not process this Install Manager definition
    [parameter(Position = 7)]
    [string[]]$ExemptMachine
    ,
    # Use to Specify the name of the Repository to use for the Definition - like PSGallery, or chocolatey, or chocolatey.licensed
    [parameter(Position = 8)]
    [ValidateNotNullOrEmpty()]
    [string]$Repository
    ,
    # Use to specify the Scope for a PowerShellGet Module
    [parameter(Position = 9)]
    [ValidateSet('AllUsers', 'CurrentUser')]
    [string]$Scope
  )

  begin
  {

  }
  process
  {
    switch ($PSCmdlet.ParameterSetName)
    {
      'Name'
      {
        $IMDefinition = @(Get-IMDefinition -Name $Name -InstallManager $InstallManager)
        switch ($IMDefinition.count)
        {
          0
          {
            Write-Warning -Message "Not Found: InstallManager Definition for $Name"
            Return
          }
          1
          {
            #All OK - found just one Definition to Set
          }
          Default
          {
            throw("Ambiguous: InstallManager Definition for $Name. Try being more specific by specifying the InstallManager.")
          }
        }
      }
    }

    foreach ($imd in $IMDefinition)
    {
      $keys = $PSBoundParameters.keys.ForEach( { $_ }) #avoid enumerating and modifying
      foreach ($k in $keys)
      {
        switch ($k -in ('RequiredVersion', 'AutoUpgrade', 'AutoRemove', 'Parameter', 'ExemptMachine', 'Repository', 'Scope'))
        {
          $true
          {
              $imd.$k = $PSBoundParameters.$k
          }
          $false
          { }
        }
      }
      if ($PSCmdlet.ShouldProcess("$imd"))
      {
        $SetConfigParams = @{
          Module      = $MyInvocation.MyCommand.ModuleName
          AllowDelete = $true
          Passthru    = $true
          Name        = "Definitions.$($imd.InstallManager).$($imd.Name)"
          Value       = $imd
        }
        Set-PSFConfig @SetConfigParams | Register-PSFConfig
      }
    }
  }

  end
  {

  }
}

###############################################################################################
# Import User's Configuration
###############################################################################################
Import-IMConfiguration
###############################################################################################
# Setup Tab Completion
###############################################################################################
# Tab Completions for IM Definition Names
$ImDefinitionsScriptBlock = {
  param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
  $MyParams = @{ }
  if ($null -ne $fakeBoundParameter.InstallManager)
  {
    $MyParams.InstallManager = $fakeBoundParameter.InstallManager
  }
  if ($null -ne $wordToComplete)
  {
    $MyParams.Name = $wordToComplete + '*'
  }
  $MyNames = Get-IMDefinition @MyParams |
    Select-Object -expandProperty Name

  foreach ($n in $MyNames)
  {
    [System.Management.Automation.CompletionResult]::new($n, $n, 'ParameterValue', $n)
  }
}

Register-ArgumentCompleter -CommandName @(
  'Get-IMDefinition'
  'Set-IMDefinition'
  'Remove-IMDefinition'
  'Update-IMInstall'
) -ParameterName 'Name' -ScriptBlock $ImDefinitionsScriptBlock