-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-TextEmbeddingsUsingAzureOpenAI.ps1
3382 lines (2993 loc) · 182 KB
/
Get-TextEmbeddingsUsingAzureOpenAI.ps1
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
# Get-TextEmbeddingsUsingOpenAI.ps1
# Version: 1.1.20240407.0
<#
.SYNOPSIS
Inputs a CSV containing text data, submit each string of text data to OpenAI's GPT-3
Embeddings API and retrieves the text embeddings, puts the text embeddings into a new
field in the CSV, and exports the CSV to a new file.
.DESCRIPTION
The Get-TextEmbeddingsUsingOpenAI.ps1 script takes a CSV containing unstructured text
data and submits it to OpenAI's GPT-3 Embeddings API. The "embeddings" are a
multi-dimensional vector representation of the text data. The script then adds a new
field containing the text embeddings and exports the CSV to a new file.
.PARAMETER InputCSVPath
Specifies the path to the input CSV file containing the data for which we will be
generating embeddings.
.PARAMETER DataFieldNameToEmbed
Specifies the name of the field in the input CSV file containing the data for which we
will be generating embeddings.
.PARAMETER NewDataFieldNameForEmbeddings
Specifies the name of the new field that will be added in the output CSV file to
contain the text embeddings. The embeddings will be stored as a semicolon-separated
string of numbers.
An additional field will be added to the input CSV in the format
($NewDataFieldNameForEmbeddings + 'Count') that will contain the number of embeddings
.PARAMETER OutputCSVPath
Specifies the path to the output CSV file that will contain the unstructured data with
the embeddings added.
.PARAMETER DoNotCheckForModuleUpdates
If supplied, the script will skip the check for PowerShell module updates. This can
speed up the script's execution time, but it is not recommended unless the user knows
that the computer's modules are already up-to-date.
.PARAMETER EntraIdTenantId
Specifies the tenant ID to use when authenticating to the Entra ID. The default
tenant ID is the one used in Frank and Danny's demo.
.PARAMETER AzureSubscriptionId
Specifies the subscription ID to use when authenticating to Azure. The default
subscription ID is the one used in Frank and Danny's demo.
.PARAMETER AzureKeyVaultName
Specifies the name of the Azure Key Vault to use when authenticating to Azure. The
default Key Vault name is the one used in Frank and Danny's demo.
.PARAMETER SecretName
Specifies the name of the secret in the Azure Key Vault. The secret must contain the
OpenAI API key.
.PARAMETER Temperature
Specifies the sampling "temperature" for the GPT model. The temperature is a value
between 0 and 1 that controls the randomness of the generated embeddings. A lower
temperature will result in more deterministic embeddings, while a higher temperature
will result in more random embeddings. The default temperature is 0.2.
.EXAMPLE
PS C:\> .\Get-TextEmbeddingsUsingOpenAI.ps1 -InputCSVPath 'C:\Users\jdoe\Documents\West Monroe Pulse Survey Comments Aug 2021.csv' -DataFieldNameToEmbed 'Comment' -OutputCSVPath 'C:\Users\jdoe\Documents\West Monroe Pulse Survey Comments Aug 2021 - With Embeddings.csv' -EntraIdTenantId '00bdb152-4d83-4056-9dce-a1a9f0210908' -AzureSubscriptionId 'a59e5b39-14b7-40dc-8052-52c7baca6f81' -AzureKeyVaultName 'PowerShellSecrets' -SecretName 'OpenAIAPIKey'
This example reads in data from the specified input CSV file, connects to an Azure Key
Vault 'PowerShellSecrets' in the Azure Subscription with ID
'a59e5b39-14b7-40dc-8052-52c7baca6f81', by authenticating with a principal in Entra ID
tenant '00bdb152-4d83-4056-9dce-a1a9f0210908', retrieves the OpenAI API key from the
key vault secret 'OpenAIAPIKey', uses the OpenAI API key to connect to OpenAI, and
retrieves "embeddings" for the text in the field named "Comment" in each row of the
input CSV. Since the NewDataFieldNameForEmbeddings parameter was not specified, the
embeddings will be stored in a new field called 'Embeddings'. Finally, the output is
written to a new CSV at the path specified by OutputCSVPath.
.OUTPUTS
None
#>
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak and Daniel Stutz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$InputCSVPath,
[Parameter(Mandatory = $true)][string]$DataFieldNameToEmbed,
[Parameter(Mandatory = $false)][string]$NewDataFieldNameForEmbeddings = 'Embeddings',
[Parameter(Mandatory = $true)][string]$OutputCSVPath,
[Parameter(Mandatory = $false)][switch]$DoNotCheckForModuleUpdates,
[Parameter(Mandatory = $false)][string]$EntraIdTenantId = '4cb2f1c9-c771-4ce5-a581-9376e59ea807',
[Parameter(Mandatory = $false)][string]$AzureSubscriptionId = 'b337b2c0-fe35-4e3c-9434-7b7a15da61b7',
[Parameter(Mandatory = $false)][string]$AzureKeyVaultName = 'powershell-conf-2024',
[Parameter(Mandatory = $false)][string]$SecretName = 'powershell-saturday-openai-key',
[Parameter(Mandatory = $false)][double]$Temperature = 0.2
)
function Get-PSVersion {
# Returns the version of PowerShell that is running, including on the original
# release of Windows PowerShell (version 1.0)
#
# Example:
# Get-PSVersion
#
# This example returns the version of PowerShell that is running. On versions
# of PowerShell greater than or equal to version 2.0, this function returns the
# equivalent of $PSVersionTable.PSVersion
#
# The function outputs a [version] object representing the version of
# PowerShell that is running
#
# PowerShell 1.0 does not have a $PSVersionTable variable, so this function
# returns [version]('1.0') on PowerShell 1.0
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
$versionThisFunction = [version]('1.0.20240326.0')
if (Test-Path variable:\PSVersionTable) {
return ($PSVersionTable.PSVersion)
} else {
return ([version]('1.0'))
}
}
function Get-PowerShellModuleUsingHashtable {
<#
.SYNOPSIS
Gets a list of installed PowerShell modules for each entry in a hashtable.
.DESCRIPTION
The Get-PowerShellModuleUsingHashtable function steps through each entry in the
supplied hashtable and gets a list of installed PowerShell modules for each entry.
.PARAMETER ReferenceToHashtable
Is a reference to a hashtable. The value of the reference should be a hashtable
with keys that are the names of PowerShell modules and values that are initialized
to be enpty arrays.
.EXAMPLE
$hashtableModuleNameToInstalledModules = @{}
$hashtableModuleNameToInstalledModules.Add('PnP.PowerShell', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Authentication', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Groups', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Users', @())
$refHashtableModuleNameToInstalledModules = [ref]$hashtableModuleNameToInstalledModules
Get-PowerShellModuleUsingHashtable -ReferenceToHashtable $refHashtableModuleNameToInstalledModules
This example gets the list of installed PowerShell modules for each of the four
modules listed in the hashtable. The list of each respective module is stored in
the value of the hashtable entry for that module.
.OUTPUTS
None
#>
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
#region DownloadLocationNotice ################################################
# The most up-to-date version of this script can be found on the author's GitHub
# repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice ################################################
# Version 1.0.20240401.0
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][ref]$ReferenceToHashtable
)
$VerbosePreferenceAtStartOfFunction = $VerbosePreference
$arrModulesToGet = @(($ReferenceToHashtable.Value).Keys)
for ($intCounter = 0; $intCounter -lt $arrModulesToGet.Count; $intCounter++) {
Write-Verbose ('Checking for ' + $arrModulesToGet[$intCounter] + ' module...')
$VerbosePreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
($ReferenceToHashtable.Value).Item($arrModulesToGet[$intCounter]) = @(Get-Module -Name ($arrModulesToGet[$intCounter]) -ListAvailable)
$VerbosePreference = $VerbosePreferenceAtStartOfFunction
}
}
function Test-PowerShellModuleInstalledUsingHashtable {
<#
.SYNOPSIS
Tests to see if a PowerShell module is installed based on entries in a hashtable.
If the PowerShell module is not installed, an error or warning message may
optionally be displayed.
.DESCRIPTION
The Test-PowerShellModuleInstalledUsingHashtable function steps through each entry
in the supplied hashtable and, if there are any modules not installed, it
optionally throws an error or warning for each module that is not installed. If all
modules are installed, the function returns $true; otherwise, if any module is not
installed, the function returns $false.
.PARAMETER ReferenceToHashtableOfInstalledModules
Is a reference to a hashtable. The hashtable must have keys that are the names of
PowerShell modules with each key's value populated with arrays of
ModuleInfoGrouping objects (the result of Get-Module).
.PARAMETER ThrowErrorIfModuleNotInstalled
Is a switch parameter. If this parameter is specified, an error is thrown for each
module that is not installed. If this parameter is not specified, no error is
thrown.
.PARAMETER ThrowWarningIfModuleNotInstalled
Is a switch parameter. If this parameter is specified, a warning is thrown for each
module that is not installed. If this parameter is not specified, or if the
ThrowErrorIfModuleNotInstalled parameter was specified, no warning is thrown.
.PARAMETER ReferenceToHashtableOfCustomNotInstalledMessages
Is a reference to a hashtable. The hashtable must have keys that are custom error
or warning messages (string) to be displayed if one or more modules are not
installed. The value for each key must be an array of PowerShell module names
(strings) relevant to that error or warning message.
If this parameter is not supplied, or if a custom error or warning message is not
supplied in the hashtable for a given module, the script will default to using the
following message:
<MODULENAME> module not found. Please install it and then try again.
You can install the <MODULENAME> PowerShell module from the PowerShell Gallery by
running the following command:
Install-Module <MODULENAME>;
If the installation command fails, you may need to upgrade the version of
PowerShellGet. To do so, run the following commands, then restart PowerShell:
Set-ExecutionPolicy Bypass -Scope Process -Force;
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;
Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;
.PARAMETER ReferenceToArrayOfMissingModules
Is a reference to an array. The array must be initialized to be empty. If any
modules are not installed, the names of those modules are added to the array.
.EXAMPLE
$hashtableModuleNameToInstalledModules = @{}
$hashtableModuleNameToInstalledModules.Add('PnP.PowerShell', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Authentication', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Groups', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Users', @())
$refHashtableModuleNameToInstalledModules = [ref]$hashtableModuleNameToInstalledModules
Get-PowerShellModuleUsingHashtable -ReferenceToHashtable $refHashtableModuleNameToInstalledModules
$hashtableCustomNotInstalledMessageToModuleNames = @{}
$strGraphNotInstalledMessage = 'Microsoft.Graph.Authentication, Microsoft.Graph.Groups, and/or Microsoft.Graph.Users modules were not found. Please install the full Microsoft.Graph module and then try again.' + [System.Environment]::NewLine + 'You can install the Microsoft.Graph PowerShell module from the PowerShell Gallery by running the following command:' + [System.Environment]::NewLine + 'Install-Module Microsoft.Graph;' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableCustomNotInstalledMessageToModuleNames.Add($strGraphNotInstalledMessage, @('Microsoft.Graph.Authentication', 'Microsoft.Graph.Groups', 'Microsoft.Graph.Users'))
$refhashtableCustomNotInstalledMessageToModuleNames = [ref]$hashtableCustomNotInstalledMessageToModuleNames
$boolResult = Test-PowerShellModuleInstalledUsingHashtable -ReferenceToHashtableOfInstalledModules $refHashtableModuleNameToInstalledModules -ThrowErrorIfModuleNotInstalled -ReferenceToHashtableOfCustomNotInstalledMessages $refhashtableCustomNotInstalledMessageToModuleNames
This example checks to see if the PnP.PowerShell, Microsoft.Graph.Authentication,
Microsoft.Graph.Groups, and Microsoft.Graph.Users modules are installed. If any of
these modules are not installed, an error is thrown for the PnP.PowerShell module
or the group of Microsoft.Graph modules, respectively, and $boolResult is set to
$false. If all modules are installed, $boolResult is set to $true.
.OUTPUTS
[boolean] - Returns $true if all modules are installed; otherwise, returns $false.
#>
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
#region DownloadLocationNotice ################################################
# The most up-to-date version of this script can be found on the author's GitHub
# repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice ################################################
# Version 1.1.20240401.0
[CmdletBinding()]
[OutputType([Boolean])]
param (
[Parameter(Mandatory = $true)][ref]$ReferenceToHashtableOfInstalledModules,
[switch]$ThrowErrorIfModuleNotInstalled,
[switch]$ThrowWarningIfModuleNotInstalled,
[Parameter(Mandatory = $false)][ref]$ReferenceToHashtableOfCustomNotInstalledMessages,
[Parameter(Mandatory = $false)][ref]$ReferenceToArrayOfMissingModules
)
$boolThrowErrorForMissingModule = $false
$boolThrowWarningForMissingModule = $false
if ($ThrowErrorIfModuleNotInstalled.IsPresent -eq $true) {
$boolThrowErrorForMissingModule = $true
} elseif ($ThrowWarningIfModuleNotInstalled.IsPresent -eq $true) {
$boolThrowWarningForMissingModule = $true
}
$boolResult = $true
$hashtableMessagesToThrowForMissingModule = @{}
$hashtableModuleNameToCustomMessageToThrowForMissingModule = @{}
if ($null -ne $ReferenceToHashtableOfCustomNotInstalledMessages) {
$arrMessages = @(($ReferenceToHashtableOfCustomNotInstalledMessages.Value).Keys)
foreach ($strMessage in $arrMessages) {
$hashtableMessagesToThrowForMissingModule.Add($strMessage, $false)
($ReferenceToHashtableOfCustomNotInstalledMessages.Value).Item($strMessage) | ForEach-Object {
$hashtableModuleNameToCustomMessageToThrowForMissingModule.Add($_, $strMessage)
}
}
}
$arrModuleNames = @(($ReferenceToHashtableOfInstalledModules.Value).Keys)
foreach ($strModuleName in $arrModuleNames) {
$arrInstalledModules = @(($ReferenceToHashtableOfInstalledModules.Value).Item($strModuleName))
if ($arrInstalledModules.Count -eq 0) {
$boolResult = $false
if ($hashtableModuleNameToCustomMessageToThrowForMissingModule.ContainsKey($strModuleName) -eq $true) {
$strMessage = $hashtableModuleNameToCustomMessageToThrowForMissingModule.Item($strModuleName)
$hashtableMessagesToThrowForMissingModule.Item($strMessage) = $true
} else {
$strMessage = $strModuleName + ' module not found. Please install it and then try again.' + [System.Environment]::NewLine + 'You can install the ' + $strModuleName + ' PowerShell module from the PowerShell Gallery by running the following command:' + [System.Environment]::NewLine + 'Install-Module ' + $strModuleName + ';' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableMessagesToThrowForMissingModule.Add($strMessage, $true)
}
if ($null -ne $ReferenceToArrayOfMissingModules) {
($ReferenceToArrayOfMissingModules.Value) += $strModuleName
}
}
}
if ($boolThrowErrorForMissingModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForMissingModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForMissingModule.Item($strMessage) -eq $true) {
Write-Error $strMessage
}
}
} elseif ($boolThrowWarningForMissingModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForMissingModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForMissingModule.Item($strMessage) -eq $true) {
Write-Warning $strMessage
}
}
}
return $boolResult
}
function Test-PowerShellModuleUpdatesAvailableUsingHashtable {
<#
.SYNOPSIS
Tests to see if updates are available for a PowerShell module based on entries in a
hashtable. If updates are available for a PowerShell module, an error or warning
message may optionally be displayed.
.DESCRIPTION
The Test-PowerShellModuleUpdatesAvailableUsingHashtable function steps through each
entry in the supplied hashtable and, if there are updates available, it optionally
throws an error or warning for each module that has updates available. If all
modules are installed and up to date, the function returns $true; otherwise, if any
module is not installed or not up to date, the function returns $false.
.PARAMETER ReferenceToHashtableOfInstalledModules
Is a reference to a hashtable. The hashtable must have keys that are the names of
PowerShell modules with each key's value populated with arrays of
ModuleInfoGrouping objects (the result of Get-Module).
.PARAMETER ThrowErrorIfModuleNotInstalled
Is a switch parameter. If this parameter is specified, an error is thrown for each
module that is not installed. If this parameter is not specified, no error is
thrown.
.PARAMETER ThrowWarningIfModuleNotInstalled
Is a switch parameter. If this parameter is specified, a warning is thrown for each
module that is not installed. If this parameter is not specified, or if the
ThrowErrorIfModuleNotInstalled parameter was specified, no warning is thrown.
.PARAMETER ThrowErrorIfModuleNotUpToDate
Is a switch parameter. If this parameter is specified, an error is thrown for each
module that is not up to date. If this parameter is not specified, no error is
thrown.
.PARAMETER ThrowWarningIfModuleNotUpToDate
Is a switch parameter. If this parameter is specified, a warning is thrown for each
module that is not up to date. If this parameter is not specified, or if the
ThrowErrorIfModuleNotUpToDate parameter was specified, no warning is thrown.
.PARAMETER ReferenceToHashtableOfCustomNotInstalledMessages
Is a reference to a hashtable. The hashtable must have keys that are custom error
or warning messages (string) to be displayed if one or more modules are not
installed. The value for each key must be an array of PowerShell module names
(strings) relevant to that error or warning message.
If this parameter is not supplied, or if a custom error or warning message is not
supplied in the hashtable for a given module, the script will default to using the
following message:
<MODULENAME> module not found. Please install it and then try again.
You can install the <MODULENAME> PowerShell module from the PowerShell Gallery by
running the following command:
Install-Module <MODULENAME>;
If the installation command fails, you may need to upgrade the version of
PowerShellGet. To do so, run the following commands, then restart PowerShell:
Set-ExecutionPolicy Bypass -Scope Process -Force;
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;
Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;
.PARAMETER ReferenceToHashtableOfCustomNotUpToDateMessages
Is a reference to a hashtable. The hashtable must have keys that are custom error
or warning messages (string) to be displayed if one or more modules are not
up to date. The value for each key must be an array of PowerShell module names
(strings) relevant to that error or warning message.
If this parameter is not supplied, or if a custom error or warning message is not
supplied in the hashtable for a given module, the script will default to using the
following message:
A newer version of the <MODULENAME> PowerShell module is available. Please consider
updating it by running the following command:
Install-Module <MODULENAME> -Force;
If the installation command fails, you may need to upgrade the version of
PowerShellGet. To do so, run the following commands, then restart PowerShell:
Set-ExecutionPolicy Bypass -Scope Process -Force;
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;
Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;
.PARAMETER ReferenceToArrayOfMissingModules
Is a reference to an array. The array must be initialized to be empty. If any
modules are not installed, the names of those modules are added to the array.
.PARAMETER ReferenceToArrayOfOutOfDateModules
Is a reference to an array. The array must be initialized to be empty. If any
modules are not up to date, the names of those modules are added to the array.
.EXAMPLE
$hashtableModuleNameToInstalledModules = @{}
$hashtableModuleNameToInstalledModules.Add('PnP.PowerShell', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Authentication', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Groups', @())
$hashtableModuleNameToInstalledModules.Add('Microsoft.Graph.Users', @())
$refHashtableModuleNameToInstalledModules = [ref]$hashtableModuleNameToInstalledModules
Get-PowerShellModuleUsingHashtable -ReferenceToHashtable $refHashtableModuleNameToInstalledModules
$hashtableCustomNotInstalledMessageToModuleNames = @{}
$strGraphNotInstalledMessage = 'Microsoft.Graph.Authentication, Microsoft.Graph.Groups, and/or Microsoft.Graph.Users modules were not found. Please install the full Microsoft.Graph module and then try again.' + [System.Environment]::NewLine + 'You can install the Microsoft.Graph PowerShell module from the PowerShell Gallery by running the following command:' + [System.Environment]::NewLine + 'Install-Module Microsoft.Graph;' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableCustomNotInstalledMessageToModuleNames.Add($strGraphNotInstalledMessage, @('Microsoft.Graph.Authentication', 'Microsoft.Graph.Groups', 'Microsoft.Graph.Users'))
$refhashtableCustomNotInstalledMessageToModuleNames = [ref]$hashtableCustomNotInstalledMessageToModuleNames
$hashtableCustomNotUpToDateMessageToModuleNames = @{}
$strGraphNotUpToDateMessage = 'A newer version of the Microsoft.Graph.Authentication, Microsoft.Graph.Groups, and/or Microsoft.Graph.Users modules was found. Please consider updating it by running the following command:' + [System.Environment]::NewLine + 'Install-Module Microsoft.Graph -Force;' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableCustomNotUpToDateMessageToModuleNames.Add($strGraphNotUpToDateMessage, @('Microsoft.Graph.Authentication', 'Microsoft.Graph.Groups', 'Microsoft.Graph.Users'))
$refhashtableCustomNotUpToDateMessageToModuleNames = [ref]$hashtableCustomNotUpToDateMessageToModuleNames
$boolResult = Test-PowerShellModuleUpdatesAvailableUsingHashtable -ReferenceToHashtableOfInstalledModules $refHashtableModuleNameToInstalledModules -ThrowErrorIfModuleNotInstalled -ThrowWarningIfModuleNotUpToDate -ReferenceToHashtableOfCustomNotInstalledMessages $refhashtableCustomNotInstalledMessageToModuleNames -ReferenceToHashtableOfCustomNotUpToDateMessages $refhashtableCustomNotUpToDateMessageToModuleNames
This example checks to see if the PnP.PowerShell, Microsoft.Graph.Authentication,
Microsoft.Graph.Groups, and Microsoft.Graph.Users modules are installed. If any of
these modules are not installed, an error is thrown for the PnP.PowerShell module
or the group of Microsoft.Graph modules, respectively, and $boolResult is set to
$false. If any of these modules are installed but not up to date, a warning
message is thrown for the PnP.PowerShell module or the group of Microsoft.Graph
modules, respectively, and $boolResult is set to false. If all modules are
installed and up to date, $boolResult is set to $true.
.OUTPUTS
[boolean] - Returns $true if all modules are installed and up to date; otherwise,
returns $false.
.NOTES
Requires PowerShell v5.0 or newer
#>
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
#region DownloadLocationNotice ################################################
# The most up-to-date version of this script can be found on the author's GitHub
# repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice ################################################
# Version 1.1.20240401.0
[CmdletBinding()]
[OutputType([Boolean])]
param (
[Parameter(Mandatory = $true)][ref]$ReferenceToHashtableOfInstalledModules,
[switch]$ThrowErrorIfModuleNotInstalled,
[switch]$ThrowWarningIfModuleNotInstalled,
[switch]$ThrowErrorIfModuleNotUpToDate,
[switch]$ThrowWarningIfModuleNotUpToDate,
[Parameter(Mandatory = $false)][ref]$ReferenceToHashtableOfCustomNotInstalledMessages,
[Parameter(Mandatory = $false)][ref]$ReferenceToHashtableOfCustomNotUpToDateMessages,
[Parameter(Mandatory = $false)][ref]$ReferenceToArrayOfMissingModules,
[Parameter(Mandatory = $false)][ref]$ReferenceToArrayOfOutdatedModules
)
function Get-PSVersion {
# Returns the version of PowerShell that is running, including on the original
# release of Windows PowerShell (version 1.0)
#
# Example:
# Get-PSVersion
#
# This example returns the version of PowerShell that is running. On versions
# of PowerShell greater than or equal to version 2.0, this function returns the
# equivalent of $PSVersionTable.PSVersion
#
# The function outputs a [version] object representing the version of
# PowerShell that is running
#
# PowerShell 1.0 does not have a $PSVersionTable variable, so this function
# returns [version]('1.0') on PowerShell 1.0
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
$versionThisFunction = [version]('1.0.20240326.0')
if (Test-Path variable:\PSVersionTable) {
return ($PSVersionTable.PSVersion)
} else {
return ([version]('1.0'))
}
}
$versionPS = Get-PSVersion
if ($versionPS -lt ([version]'5.0')) {
Write-Warning 'Test-PowerShellModuleUpdatesAvailableUsingHashtable requires PowerShell version 5.0 or newer.'
return $false
}
$boolThrowErrorForMissingModule = $false
$boolThrowWarningForMissingModule = $false
if ($ThrowErrorIfModuleNotInstalled.IsPresent -eq $true) {
$boolThrowErrorForMissingModule = $true
} elseif ($ThrowWarningIfModuleNotInstalled.IsPresent -eq $true) {
$boolThrowWarningForMissingModule = $true
}
$boolThrowErrorForOutdatedModule = $false
$boolThrowWarningForOutdatedModule = $false
if ($ThrowErrorIfModuleNotUpToDate.IsPresent -eq $true) {
$boolThrowErrorForOutdatedModule = $true
} elseif ($ThrowWarningIfModuleNotUpToDate.IsPresent -eq $true) {
$boolThrowWarningForOutdatedModule = $true
}
$VerbosePreferenceAtStartOfFunction = $VerbosePreference
$boolResult = $true
$hashtableMessagesToThrowForMissingModule = @{}
$hashtableModuleNameToCustomMessageToThrowForMissingModule = @{}
if ($null -ne $ReferenceToHashtableOfCustomNotInstalledMessages) {
$arrMessages = @(($ReferenceToHashtableOfCustomNotInstalledMessages.Value).Keys)
foreach ($strMessage in $arrMessages) {
$hashtableMessagesToThrowForMissingModule.Add($strMessage, $false)
($ReferenceToHashtableOfCustomNotInstalledMessages.Value).Item($strMessage) | ForEach-Object {
$hashtableModuleNameToCustomMessageToThrowForMissingModule.Add($_, $strMessage)
}
}
}
$hashtableMessagesToThrowForOutdatedModule = @{}
$hashtableModuleNameToCustomMessageToThrowForOutdatedModule = @{}
if ($null -ne $ReferenceToHashtableOfCustomNotUpToDateMessages) {
$arrMessages = @(($ReferenceToHashtableOfCustomNotUpToDateMessages.Value).Keys)
foreach ($strMessage in $arrMessages) {
$hashtableMessagesToThrowForOutdatedModule.Add($strMessage, $false)
($ReferenceToHashtableOfCustomNotUpToDateMessages.Value).Item($strMessage) | ForEach-Object {
$hashtableModuleNameToCustomMessageToThrowForOutdatedModule.Add($_, $strMessage)
}
}
}
$arrModuleNames = @(($ReferenceToHashtableOfInstalledModules.Value).Keys)
foreach ($strModuleName in $arrModuleNames) {
$arrInstalledModules = @(($ReferenceToHashtableOfInstalledModules.Value).Item($strModuleName))
if ($arrInstalledModules.Count -eq 0) {
$boolResult = $false
if ($hashtableModuleNameToCustomMessageToThrowForMissingModule.ContainsKey($strModuleName) -eq $true) {
$strMessage = $hashtableModuleNameToCustomMessageToThrowForMissingModule.Item($strModuleName)
$hashtableMessagesToThrowForMissingModule.Item($strMessage) = $true
} else {
$strMessage = $strModuleName + ' module not found. Please install it and then try again.' + [System.Environment]::NewLine + 'You can install the ' + $strModuleName + ' PowerShell module from the PowerShell Gallery by running the following command:' + [System.Environment]::NewLine + 'Install-Module ' + $strModuleName + ';' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableMessagesToThrowForMissingModule.Add($strMessage, $true)
}
if ($null -ne $ReferenceToArrayOfMissingModules) {
($ReferenceToArrayOfMissingModules.Value) += $strModuleName
}
} else {
$versionNewestInstalledModule = ($arrInstalledModules | ForEach-Object { [version]($_.Version) } | Sort-Object)[-1]
$arrModuleNewestInstalledModule = @($arrInstalledModules | Where-Object { ([version]($_.Version)) -eq $versionNewestInstalledModule })
# In the event there are multiple installations of the same version, reduce to a
# single instance of the module
if ($arrModuleNewestInstalledModule.Count -gt 1) {
$moduleNewestInstalled = @($arrModuleNewestInstalledModule | Select-Object -Unique)[0]
} else {
$moduleNewestInstalled = $arrModuleNewestInstalledModule[0]
}
$VerbosePreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
$moduleNewestAvailable = Find-Module -Name $strModuleName -ErrorAction SilentlyContinue
$VerbosePreference = $VerbosePreferenceAtStartOfFunction
if ($null -ne $moduleNewestAvailable) {
if ($moduleNewestAvailable.Version -gt $moduleNewestInstalled.Version) {
# A newer version is available
$boolResult = $false
if ($hashtableModuleNameToCustomMessageToThrowForOutdatedModule.ContainsKey($strModuleName) -eq $true) {
$strMessage = $hashtableModuleNameToCustomMessageToThrowForOutdatedModule.Item($strModuleName)
$hashtableMessagesToThrowForOutdatedModule.Item($strMessage) = $true
} else {
$strMessage = 'A newer version of the ' + $strModuleName + ' PowerShell module is available. Please consider updating it by running the following command:' + [System.Environment]::NewLine + 'Install-Module ' + $strModuleName + ' -Force;' + [System.Environment]::NewLine + [System.Environment]::NewLine + 'If the installation command fails, you may need to upgrade the version of PowerShellGet. To do so, run the following commands, then restart PowerShell:' + [System.Environment]::NewLine + 'Set-ExecutionPolicy Bypass -Scope Process -Force;' + [System.Environment]::NewLine + '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;' + [System.Environment]::NewLine + 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force;' + [System.Environment]::NewLine + 'Install-Module PowerShellGet -MinimumVersion 2.2.4 -SkipPublisherCheck -Force -AllowClobber;' + [System.Environment]::NewLine + [System.Environment]::NewLine
$hashtableMessagesToThrowForOutdatedModule.Add($strMessage, $true)
}
if ($null -ne $ReferenceToArrayOfOutdatedModules) {
($ReferenceToArrayOfOutdatedModules.Value) += $strModuleName
}
}
} else {
# Couldn't find the module in the PowerShell Gallery
}
}
}
if ($boolThrowErrorForMissingModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForMissingModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForMissingModule.Item($strMessage) -eq $true) {
Write-Error $strMessage
}
}
} elseif ($boolThrowWarningForMissingModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForMissingModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForMissingModule.Item($strMessage) -eq $true) {
Write-Warning $strMessage
}
}
}
if ($boolThrowErrorForOutdatedModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForOutdatedModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForOutdatedModule.Item($strMessage) -eq $true) {
Write-Error $strMessage
}
}
} elseif ($boolThrowWarningForOutdatedModule -eq $true) {
$arrMessages = @($hashtableMessagesToThrowForOutdatedModule.Keys)
foreach ($strMessage in $arrMessages) {
if ($hashtableMessagesToThrowForOutdatedModule.Item($strMessage) -eq $true) {
Write-Warning $strMessage
}
}
}
return $boolResult
}
function Copy-Object {
#region FunctionHeader #########################################################
# This function is needed because PowerShell does not simply let you copy an object
# of any complexity to another using the equal sign operator. If you were to use
# the equal sign operator, it copies the pointer to the object - meaning that the
# two variables that you thought were copies of each other are actually the same
# object.
#
# Four positional arguments are required:
#
# The first argument is a reference to an output object to which the copy will
# occur.
#
# The second argument is a reference to a source object from which the copy will
# occur.
#
# The third argument is optional. If specified, it is an integer between 1 and
# [int]::MaxValue that indicates the depth of the copy operation (i.e., how many
# levels deep to copy nested objects, recursively). If set to $null or not
# specified, the default copy depth is 2.
#
# The fourth argument is optional. If specified, it is a boolean indicating whether
# the source object should be considered "safe", i.e., generated from a trusted
# process and not possible to contain malicious code (see notes). If set to $null
# or not specified, the default is $false.
#
# The function returns an integer indicating the success/failure of the process:
#
# 0 indicates success, that the source object was marked as serializable, the
# function call indicated it was generated from a trusted process and not possible
# to contain malicious code, and that the object was successfully copied using
# BinaryFormatter - meaning that we are pretty well guaranteed that the source
# object was copied in its entirety.
#
# 1 indicates success, but that the source object was either not marked as
# serializable, or that it was not indicated to be generated from a trusted
# process/possible to contain malicious code. In this case, the copy depth was used
# to determine how "deeply" to copy nested objects. The destination object is not
# guaranteed to be an exact copy of the source.
#
# 2 indicates failure; the object was not able to be copied
#
# Example usage:
#
# # Example 1: Fast object copy; this method *might* miss nested object data on
# # complex objects
# $SourceObject = @([AppDomain]::CurrentDomain.GetAssemblies())
# $DestinationObject = $null
# $intReturnCode = Copy-Object ([ref]$DestinationObject) ([ref]$SourceObject) 1
# # Note 1: @(@($SourceObject)[0].Modules)[0].Assembly is not equal to $null
# # Note 2: @(@($DestinationObject)[0].Modules)[0].Assembly is equal to $null
# # because the copy depth is 1
# # Note 3: On the plus side, this example takes 0.5 - 2 seconds to complete -
# # pretty fast.
#
# # Example 2: More-robust copy; this method can still miss nested object data on
# # complex objects but is less likely to do so
# $SourceObject = @([AppDomain]::CurrentDomain.GetAssemblies())
# $DestinationObject = $null
# $intReturnCode = Copy-Object ([ref]$DestinationObject) ([ref]$SourceObject) 3
# # Note 1: @(@($SourceObject)[0].Modules)[0].Assembly is not equal to $null
# # Note 2: @(@($DestinationObject)[0].Modules)[0].Assembly is also not equal to
# # $null because we copied the object "deeply enough".
# # Note 3: This command could take approximately 6-20 minutes to complete (!).
#
# # Example 3: Copy an object that is marked as serializable and generated from a
# # trusted process:
# $SourceObject = New-Object 'System.Collections.Generic.List[System.String]'
# for ($intCounter = 1; $intCounter -le 10000; $intCounter++) {
# $SourceObject.Add('Item' + ([string]$intCounter))
# }
# $DestinationObject = $null
# $intReturnCode = Copy-Object ([ref]$DestinationObject) ([ref]$SourceObject) 3 $true
#
# Note: Copying an object that is marked as serializable is possible in its
# entirety is possible by setting the fourth parameter to $true, which will tell
# this function to use BinaryFormatter to perform the copy. However,
# BinaryFormatter has inherent security vulnerabilities and Microsoft has
# discouraged its use. See:
# https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
#
# Note: This function is compatible all the way back to PowerShell v1.0.
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #########################################################
#region License ################################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion License ################################################################
#region DownloadLocationNotice #################################################
# The most up-to-date version of this script can be found on the author's GitHub
# repository at https://github.com/franklesniak/Copy-Object
#endregion DownloadLocationNotice #################################################
#region FunctionsToSupportErrorHandling ########################################
function Get-ReferenceToLastError {
#region FunctionHeader #####################################################
# Function returns $null if no errors on on the $error stack;
# Otherwise, function returns a reference (memory pointer) to the last error
# that occurred.
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
if ($error.Count -gt 0) {
[ref]($error[0])
} else {
$null
}
}
function Test-ErrorOccurred {
#region FunctionHeader #####################################################
# Function accepts two positional arguments:
#
# The first argument is a reference (memory pointer) to the last error that had
# occurred prior to calling the command in question - that is, the command that
# we want to test to see if an error occurred.
#
# The second argument is a reference to the last error that had occurred as-of
# the completion of the command in question.
#
# Function returns $true if it appears that an error occurred; $false otherwise
#
# Version: 1.0.20240127.0
#endregion FunctionHeader #####################################################
#region License ############################################################
# Copyright (c) 2024 Frank Lesniak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#endregion License ############################################################
#region DownloadLocationNotice #############################################
# The most up-to-date version of this script can be found on the author's
# GitHub repository at https://github.com/franklesniak/PowerShell_Resources
#endregion DownloadLocationNotice #############################################
# TO-DO: Validate input
$boolErrorOccurred = $false
if (($null -ne ($args[0])) -and ($null -ne ($args[1]))) {
# Both not $null
if ((($args[0]).Value) -ne (($args[1]).Value)) {
$boolErrorOccurred = $true
}
} else {
# One is $null, or both are $null
# NOTE: ($args[0]) could be non-null, while ($args[1])
# could be null if $error was cleared; this does not indicate an error.
# So: