-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path01_ConfigureEnv.ps1
3478 lines (3361 loc) · 140 KB
/
01_ConfigureEnv.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
#Requires -Version 2.0
<#
Copyright (c) Alya Consulting, 2019-2024
This file is part of the Alya Base Configuration.
https://alyaconsulting.ch/Loesungen/BasisKonfiguration
The Alya Base Configuration is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Alya Base Configuration is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details: https://www.gnu.org/licenses/gpl-3.0.txt
Diese Datei ist Teil der Alya Basis Konfiguration.
https://alyaconsulting.ch/Loesungen/BasisKonfiguration
Die Alya Basis Konfiguration ist eine Freie Software: Sie können sie unter den
Bedingungen der GNU General Public License, wie von der Free Software
Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder neueren
veröffentlichten Version, weiter verteilen und/oder modifizieren.
Die Alya Basis Konfiguration wird in der Hoffnung, dass sie nützlich sein wird,
aber OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
Siehe die GNU General Public License fuer weitere Details:
https://www.gnu.org/licenses/gpl-3.0.txt
History:
Date Author Description
---------- -------------------- ----------------------------
06.11.2019 Konrad Brunner Initial version
25.02.2020 Konrad Brunner Changed login functions
02.03.2020 Konrad Brunner Added network functions
10.03.2020 Konrad Brunner Added wvd stuff
07.04.2020 Konrad Brunner Added aip stuff
21.04.2020 Konrad Brunner Service principal recognition in LoginTo-Az
09.09.2020 Konrad Brunner Changed context naming
14.09.2020 Konrad Brunner Moved Alya global variables to data\ConfigureEnv.ps1
17.09.2020 Konrad Brunner Added custom property checks
24.09.2020 Konrad Brunner LoginTo-EXO and LoginTo-IPPS
12.04.2021 Konrad Brunner Added DevOps login
12.07.2021 Konrad Brunner Added own module path
04.10.2021 Konrad Brunner Proxy default credentials
04.08.2022 Konrad Brunner Added simple password generator
18.08.2022 Konrad Brunner Select-Item
18.10.2022 Konrad Brunner LoginTo-MgGraph
20.12.2022 Konrad Brunner LoginTo-DataGateway
22.03.2023 Konrad Brunner Check for existing PowerShell Modules in default module path
10.04.2023 Konrad Brunner Reuse connection in PnP Powershell
20.04.2023 Konrad Brunner Added Mime Mapping function for PS7
14.05.2023 Konrad Brunner Fixed package management update
12.06.2023 Konrad Brunner Scripts path
22.07.2023 Konrad Brunner Added non Public Cloud Environment Support
16.10.2023 Konrad Brunner Install-ModuleIfNotInstalled new param: doNotLoadModules
01.05.2024 Konrad Brunner Supporting MAC
13.09.2024 Konrad Brunner AlyaPnPAppId
04.12.2024 Konrad Brunner New EXO login behaviour
#>
[CmdletBinding()]
Param(
)
<# COLORS will be overwritten by custom configuration #>
$CommandInfo = "Cyan"
$CommandSuccess = "Green"
$CommandError = "Red"
$CommandWarning = "Yellow"
$AlyaColor = "White"
$TitleColor = "Green"
$MenuColor = "Magenta"
$QuestionColor = "Magenta"
<# ROOT PATHS #>
$AlyaAzureEnvironment = "AzureCloud"
$AlyaPnpEnvironment = "Production"
$AlyaGraphEnvironment = "Global"
$AlyaExchangeEnvironment = "O365Default"
$AlyaSharePointEnvironment = "Default"
$AlyaTeamsEnvironment = $null
$AlyaGraphAppId = $null
$AlyaPnPAppId = $null
$AlyaGraphEndpoint = "https://graph.microsoft.com"
$AlyaADGraphEndpoint = "https://graph.windows.net"
$AlyaOpenIDEndpoint = "https://login.microsoftonline.com"
$AlyaLoginEndpoint = "https://login.microsoftonline.com"
$AlyaM365AdminPortalRoot = "https://admin.microsoft.com/AdminPortal"
$AlyaRoot = "$PSScriptRoot"
$AlyaLogs = "$AlyaRoot\_logs"
$AlyaTemp = "$AlyaRoot\_temp"
$AlyaLocal = "$AlyaRoot\_local"
$AlyaData = "$AlyaRoot\data"
$AlyaScripts = "$AlyaRoot\scripts"
$AlyaSolutions = "$AlyaRoot\solutions"
$AlyaTools = "$AlyaRoot\tools"
$AlyaEnvSwitch = ""
$AlyaModuleVersionOverwrite = @( @{Name="PnP.PowerShell";Version="2.4.0"} )
$AlyaPackageVersionOverwrite = @( <#@{Name="Selenium.WebDriver";Version="4.10.0"}#> )
if (-Not (Test-Path $AlyaTemp))
{
$null = New-Item -Path $AlyaTemp -ItemType "Directory" -Force
}
# Switching env if required
if ((Test-Path $AlyaLocal\EnvSwitch.ps1))
{
Write-Host "Switching environment" -ForegroundColor $MenuColor
. $AlyaLocal\EnvSwitch.ps1
Write-Host " to $AlyaEnvSwitch" -ForegroundColor $MenuColor
}
# Loading custom configuration
Write-Host "Loading configuration" -ForegroundColor $CommandInfo
if ((Test-Path $PSScriptRoot\data\ConfigureEnv.ps1))
{
. $PSScriptRoot\data\ConfigureEnv$AlyaEnvSwitch.ps1
}
<# POWERSHELL #>
$Global:ErrorActionPreference = "Stop"
$Global:ProgressPreference = "SilentlyContinue"
$AlyaIsPsCore = ($PSVersionTable).PSEdition -eq "Core"
$AlyaIsPsUnix = ($PSVersionTable).Platform -eq "Unix"
$AlyaUtf8Encoding = "UTF8"
if ($AlyaIsPsCore) { $AlyaUtf8Encoding = "utf8BOM" }
$AlyaPowerShellExe = "powershell.exe"
if ($AlyaIsPsCore) { $AlyaPowerShellExe = "pwsh.exe" }
$AlyaPathSep = ";"
if ($AlyaIsPsUnix) {
$AlyaPowerShellExe = "pwsh"
$AlyaPathSep = ":"
}
<# TLS Connections #>
[Net.ServicePointManager]::SecurityProtocol = @([Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls13)
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
<# OTHER PATHS #>
$AlyaDefaultModulePath = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "WindowsPowerShell\Modules"
$AlyaDefaultModulePathCore = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "PowerShell\Modules"
$AlyaDefaultScriptPath = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "WindowsPowerShell\Scripts"
$AlyaDefaultScriptPathCore = Join-Path ([Environment]::GetFolderPath("MyDocuments")) "PowerShell\Scripts"
if (-Not $AlyaModulePath) { $AlyaModulePath = $AlyaDefaultModulePath }
if (-Not $AlyaScriptPath) { $AlyaScriptPath = $AlyaDefaultScriptPath }
$AlyaOfficeRoot = "C:\Program Files\Microsoft Office\root\Office16"
$AlyaGitRoot = Join-Path (Join-Path $AlyaRoot "tools") "git"
$AlyaDeployToolRoot = Join-Path (Join-Path $AlyaRoot "tools") "officedeploy"
if (-Not (Test-Path "$AlyaLogs"))
{
$tmp = New-Item -Path "$AlyaLogs" -ItemType Directory -Force
}
#Env required for WinPE and sticks
if ((Test-Path "$($AlyaTools)\WindowsPowerShell\Modules") -and `
-Not $env:PSModulePath.Contains("$($AlyaTools)\WindowsPowerShell\Modules"))
{
Write-Host "Adding tools\WindowsPowerShell\Modules to PSModulePath"
if (-Not $env:PSModulePath.StartsWith("$($AlyaTools)\WindowsPowerShell\Modules"))
{
$env:PSModulePath = "$($AlyaTools)\WindowsPowerShell\Modules$AlyaPathSep"+$env:PSModulePath
}
}
if ((Test-Path "$($AlyaTools)\WindowsPowerShell\Scripts") -and `
-Not $env:PATH.Contains("$($AlyaTools)\WindowsPowerShell\Scripts"))
{
Write-Host "Adding tools\WindowsPowerShell\Scripts to Path"
if (-Not $env:PATH.StartsWith("$($AlyaTools)\WindowsPowerShell\Scripts"))
{
$env:PATH = "$($AlyaTools)\WindowsPowerShell\Scripts$AlyaPathSep"+$env:PATH
}
}
# Loading local custom configuration
$AlyaPnpConnectionsDefined = Get-Variable -Name "AlyaPnpConnections" -Scope Global -ErrorAction SilentlyContinue
if (-Not $AlyaPnpConnectionsDefined) { $Global:AlyaPnpConnections = @() }
if ((Test-Path $AlyaLocal\ConfigureEnv.ps1))
{
Write-Host "Loading local configuration" -ForegroundColor $CommandInfo
. $AlyaLocal\ConfigureEnv.ps1
}
if ($AlyaModulePath -ne $AlyaDefaultModulePath -and $AlyaModulePath -ne $AlyaDefaultModulePathCore)
{
if (((Test-Path $AlyaDefaultModulePath) -or (Test-Path $AlyaDefaultModulePathCore)) -and -not $Global:AlyaDefaultModulePathWarningDone)
{
$Global:AlyaDefaultModulePathWarningDone = $true
Write-Host "You have specified the variable AlyaModulePath and modules are present in the default module path:" -ForegroundColor Red
Write-Host "$AlyaDefaultModulePath" -ForegroundColor Red
Write-Host "$AlyaDefaultModulePathCore" -ForegroundColor Red
Write-Host "This can lead to unexpected behaviour!" -ForegroundColor Red
Write-Host "We suggest you rename default module path to prevent from issues and rerun this powershell session." -ForegroundColor Red
}
if (-Not (Test-Path $AlyaModulePath))
{
New-Item -Path $AlyaModulePath -ItemType Directory -Force
}
if (-Not $env:PSModulePath.Contains("$($AlyaModulePath)"))
{
$env:PSModulePath = "$($AlyaModulePath)$AlyaPathSep"+$env:PSModulePath
}
}
if ($AlyaScriptPath -ne $AlyaDefaultScriptPath -and $AlyaScriptPath -ne $AlyaDefaultScriptPathCore)
{
if (-Not (Test-Path $AlyaScriptPath))
{
New-Item -Path $AlyaScriptPath -ItemType Directory -Force
}
}
if ($AlyaIsPsCore)
{
if (-Not $env:PATH.Contains("$($AlyaDefaultScriptPathCore)"))
{
$env:PATH = "$($AlyaDefaultScriptPathCore)$AlyaPathSep$($env:PATH)"
}
}
if (-Not $env:PATH.Contains("$($AlyaScriptPath)"))
{
$env:PATH = "$($AlyaScriptPath)$AlyaPathSep$($env:PATH)"
}
<# CLIENT SETTINGS #>
$AlyaOfficeToolsOnTaskbar = @("OUTLOOK.EXE", "WINWORD.EXE", "EXCEL.EXE", "POWERPNT.EXE") #WINPROJ.EXE, VISIO.EXE, ONENOTE.EXE, MSPUB.EXE, MSACCESS.EXE
<# URLS #>
$AlyaGitDownload = "https://git-scm.com/downloads/win"
$AlyaDeployToolDownload = "https://www.microsoft.com/en-us/download/details.aspx?id=49117"
$AlyaAipClientDownload = "https://www.microsoft.com/en-us/download/details.aspx?id=53018"
$AlyaIntuneWinAppUtilDownload = "https://github.com/microsoft/Microsoft-Win32-Content-Prep-Tool.git"
$AlyaAzCopyDownload = "https://aka.ms/downloadazcopy-v10-windows"
$AlyaAdkDownload = "https://go.microsoft.com/fwlink/?linkid=2120254"
$AlyaAdkPeDownload = "https://go.microsoft.com/fwlink/?linkid=2120253"
<# LOCAL CONFIGURATION #>
$Global:AlyaLocalConfig = [ordered]@{
user= @{
email = ""
ssh = ""
}
}
Function Save-LocalConfig()
{
$tmp = $Global:AlyaLocalConfig | ConvertTo-Json | Set-Content -Path "$AlyaLocal\LocalConfig.json" -Encoding UTF8 -Force
}
Function Read-LocalConfig()
{
$Global:AlyaLocalConfig = Get-Content -Path "$AlyaLocal\LocalConfig.json" -Raw -Encoding $AlyaUtf8Encoding | ConvertFrom-Json
}
if (-Not (Test-Path "$AlyaLocal\LocalConfig.json"))
{
$tmp = New-Item -Path "$AlyaLocal" -ItemType Directory -Force
}
if ((Test-Path "$AlyaLocal\LocalConfig.json"))
{
Read-LocalConfig
}
else
{
Save-LocalConfig
}
<# GLOBAL CONFIGURATION #>
$Global:AlyaGlobalConfig = [ordered]@{
source= @{
devops = ""
}
}
Function Save-GlobalConfig()
{
$tmp = $Global:AlyaGlobalConfig | ConvertTo-Json | Set-Content -Path "$AlyaData\GlobalConfig.json" -Encoding UTF8 -Force
}
Function Read-GlobalConfig()
{
$Global:AlyaGlobalConfig = Get-Content -Path "$AlyaData\GlobalConfig.json" -Raw -Encoding $AlyaUtf8Encoding | ConvertFrom-Json
}
if (-Not (Test-Path "$AlyaData\GlobalConfig.json"))
{
$tmp = New-Item -Path "$AlyaData\" -ItemType Directory -Force
}
if ((Test-Path "$AlyaData\GlobalConfig.json"))
{
Read-GlobalConfig
}
else
{
Save-GlobalConfig
}
<# OTHERS #>
$AlyaTimeString = (Get-Date).ToString("yyyyMMddHHmmssfff")
<# MISC HELPER FUNCTIONS #>
function IIf($If, $Then, $Else) {
If ($If -IsNot "Boolean") {$_ = $If}
If ($If) {If ($Then -is "ScriptBlock") {&$Then} Else {$Then}}
Else {If ($Else -is "ScriptBlock") {&$Else} Else {$Else}}
}
function Get-ActualLoadedLibraries ()
{
[System.AppDomain]::CurrentDomain.GetAssemblies() | Select-Object -Property FullName,Location | Sort-Object -Property FullName | Format-List
[System.AppDomain]::CurrentDomain.GetAssemblies() | Select-Object -Property FullName,Location | Sort-Object -Property FullName | Format-Table
}
function Set-AllCallsToVerbose
{
$PSDefaultParameterValues = @{"*:Verbose"=$True}
}
function Get-PowerShellDefaultEncoding
{
[psobject].Assembly.GetTypes() | Where-Object { $_.Name -eq 'ClrFacade'} |
ForEach-Object {
$_.GetMethod('GetDefaultEncoding', [System.Reflection.BindingFlags]'nonpublic,static').Invoke($null, @())
}
}
function Get-PowerShellEncodingIfNoBom
{
$badBytes = [byte[]]@(0xC3, 0x80)
$utf8Str = [System.Text.Encoding]::UTF8.GetString($badBytes)
$bytes = [System.Text.Encoding]::ASCII.GetBytes('Write-Output "') + [byte[]]@(0xC3, 0x80) + [byte[]]@(0x22)
$path = Join-Path ([System.IO.Path]::GetTempPath()) 'encodingtest.ps1'
try
{
[System.IO.File]::WriteAllBytes($path, $bytes)
switch (& $path)
{
$utf8Str
{
return 'UTF-8'
break
}
default
{
return 'Windows-1252'
break
}
}
}
finally
{
Remove-Item $path
}
}
function Invoke-WebRequestIndep ()
{
Param(
[Switch]$UseBasicParsing,
[System.Uri]$Uri,
[System.Version]$HttpVersion,
[Microsoft.PowerShell.Commands.WebRequestSession]$WebSession,
[System.String]$SessionVariable,
[Switch]$AllowUnencryptedAuthentication,
[Object]$Authentication,
[System.Management.Automation.PSCredential]$Credential,
[Switch]$UseDefaultCredentials,
[System.String]$CertificateThumbprint,
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[Switch]$SkipCertificateCheck,
[Switch]$SkipHeaderValidation,
[Object]$SslProtocol,
[System.Security.SecureString]$Token,
[System.String]$UserAgent,
[Switch]$DisableKeepAlive,
[System.Int32]$TimeoutSec,
[System.Collections.IDictionary]$Headers,
[System.Int32]$MaximumRedirection,
[System.Int32]$MaximumRetryCount,
[System.Int32]$RetryIntervalSec,
[Object]$Method,
[System.String]$CustomMethod,
[Switch]$NoProxy,
[System.Uri]$Proxy,
[System.Management.Automation.PSCredential]$ProxyCredential,
[Switch]$ProxyUseDefaultCredentials,
[System.Object]$Body,
[System.Collections.IDictionary]$Form,
[System.String]$ContentType,
[System.String]$TransferEncoding,
[System.String]$InFile,
[System.String]$OutFile,
[Switch]$AllowInsecureRedirect,
[Switch]$PassThru,
[Switch]$Resume,
[Switch]$SkipHttpErrorCheck,
[Object]$Verbose,
[Object]$Debug,
[Object]$ErrorAction,
[Object]$WarningAction,
[Object]$InformationAction,
[Object]$ErrorVariable,
[Object]$WarningVariable,
[Object]$InformationVariable,
[Object]$OutVariable,
[Object]$OutBuffer,
[Object]$PipelineVariable
)
$parms = @{}
$pkeys = $PSBoundParameters.Keys
if ($AlyaIsPsCore) {
if ($pkeys -contains "SkipHttpErrorCheck") { $parms["SkipHttpErrorCheck"] = $null }
if ($pkeys -contains "HttpVersion") { $parms["HttpVersion"] = $HttpVersion }
if ($pkeys -contains "AllowUnencryptedAuthentication") { $parms["AllowUnencryptedAuthentication"] = $null }
if ($pkeys -contains "Authentication") { $parms["Authentication"] = $Authentication }
if ($pkeys -contains "SkipCertificateCheck") { $parms["SkipCertificateCheck"] = $null }
if ($pkeys -contains "SslProtocol") { $parms["SslProtocol"] = $SslProtocol }
if ($pkeys -contains "Token") { $parms["Token"] = $Token }
if ($pkeys -contains "MaximumRetryCount") { $parms["MaximumRetryCount"] = $MaximumRetryCount }
if ($pkeys -contains "RetryIntervalSec") { $parms["RetryIntervalSec"] = $RetryIntervalSec }
if ($pkeys -contains "CustomMethod") { $parms["CustomMethod"] = $CustomMethod }
if ($pkeys -contains "NoProxy") { $parms["NoProxy"] = $null }
if ($pkeys -contains "Form") { $parms["Form"] = $Form }
if ($pkeys -contains "Resume") { $parms["Resume"] = $null }
if ($pkeys -contains "SkipHeaderValidation") { $parms["SkipHeaderValidation"] = $null }
if ($pkeys -contains "PreserveAuthorizationOnRedirect") { $parms["PreserveAuthorizationOnRedirect"] = $null }
if ($pkeys -contains "AllowInsecureRedirect") { $parms["AllowInsecureRedirect"] = $null }
}
if ($pkeys -contains "UseBasicParsing") { $parms["UseBasicParsing"] = $null }
if ($pkeys -contains "Uri") { $parms["Uri"] = $Uri }
if ($pkeys -contains "WebSession") { $parms["WebSession"] = $WebSession }
if ($pkeys -contains "SessionVariable") { $parms["SessionVariable"] = $SessionVariable }
if ($pkeys -contains "Credential") { $parms["Credential"] = $Credential }
if ($pkeys -contains "UseDefaultCredentials") { $parms["UseDefaultCredentials"] = $null }
if ($pkeys -contains "CertificateThumbprint") { $parms["CertificateThumbprint"] = $CertificateThumbprint }
if ($pkeys -contains "Certificate") { $parms["Certificate"] = $Certificate }
if ($pkeys -contains "UserAgent") { $parms["UserAgent"] = $UserAgent }
if ($pkeys -contains "DisableKeepAlive") { $parms["DisableKeepAlive"] = $null }
if ($pkeys -contains "TimeoutSec") { $parms["TimeoutSec"] = $TimeoutSec }
if ($pkeys -contains "Headers") { $parms["Headers"] = $Headers }
if ($pkeys -contains "MaximumRedirection") { $parms["MaximumRedirection"] = $MaximumRedirection }
if ($pkeys -contains "Method") { $parms["Method"] = $Method }
if ($pkeys -contains "Proxy") { $parms["Proxy"] = $Proxy }
if ($pkeys -contains "ProxyCredential") { $parms["ProxyCredential"] = $ProxyCredential }
if ($pkeys -contains "ProxyUseDefaultCredentials") { $parms["ProxyUseDefaultCredentials"] = $null }
if ($pkeys -contains "Body") { $parms["Body"] = $Body }
if ($pkeys -contains "ContentType") { $parms["ContentType"] = $ContentType }
if ($pkeys -contains "TransferEncoding") { $parms["TransferEncoding"] = $TransferEncoding }
if ($pkeys -contains "InFile") { $parms["InFile"] = $InFile }
if ($pkeys -contains "OutFile") { $parms["OutFile"] = $OutFile }
if ($pkeys -contains "PassThru") { $parms["PassThru"] = $null }
if ($pkeys -contains "Verbose") { $parms["Verbose"] = $null }
if ($pkeys -contains "Debug") { $parms["Debug"] = $null }
if ($pkeys -contains "ErrorAction") { $parms["ErrorAction"] = $ErrorAction }
if ($pkeys -contains "WarningAction") { $parms["WarningAction"] = $WarningAction }
if ($pkeys -contains "InformationAction") { $parms["InformationAction"] = $InformationAction }
if ($pkeys -contains "ErrorVariable") { $parms["ErrorVariable"] = $ErrorVariable }
if ($pkeys -contains "WarningVariable") { $parms["WarningVariable"] = $WarningVariable }
if ($pkeys -contains "InformationVariable") { $parms["InformationVariable"] = $InformationVariable }
if ($pkeys -contains "OutVariable") { $parms["OutVariable"] = $OutVariable }
if ($pkeys -contains "OutBuffer") { $parms["OutBuffer"] = $OutBuffer }
if ($pkeys -contains "PipelineVariable") { $parms["PipelineVariable"] = $PipelineVariable }
return Invoke-WebRequest @parms
}
function Get-MimeType()
{
[CmdletBinding()]
Param(
[string]$Extension = $null
)
$mimeType = $null
if ( $null -ne $extension )
{
$drive = Get-PSDrive "HKCR" -ErrorAction SilentlyContinue
if ( $null -eq $drive )
{
$drive = New-PSDrive -Name "HKCR" -PSProvider Registry -Root HKEY_CLASSES_ROOT
}
$mimeType = (Get-ItemProperty "HKCR:$extension")."Content Type"
}
return $mimeType
}
function Remove-OneDriveItemRecursive
{
[cmdletbinding()]
param(
[string] $Path
)
if ($Path -and (Test-Path -LiteralPath $Path))
{
$Items = Get-ChildItem -LiteralPath $Path -File -Recurse
foreach ($Item in $Items)
{
try
{
$Item.Delete()
} catch
{
throw "Remove-OneDriveItemRecursive - Couldn't delete $($Item.FullName), error: $($_.Exception.Message)"
}
}
$Items = Get-ChildItem -LiteralPath $Path -Directory -Recurse | Sort-object -Property { $_.FullName.Length } -Descending
foreach ($Item in $Items)
{
try
{
$Item.Delete()
} catch
{
throw "Remove-OneDriveItemRecursive - Couldn't delete $($Item.FullName), error: $($_.Exception.Message)"
}
}
try
{
(Get-Item -LiteralPath $Path).Delete()
} catch
{
throw "Remove-OneDriveItemRecursive - Couldn't delete $($Path), error: $($_.Exception.Message)"
}
} else
{
Write-Warning "Remove-OneDriveItemRecursive - Path $Path doesn't exists. Skipping. "
}
}
function Is-InternetConnected()
{
$var = Get-Variable -Name "AlyaIsInternetConnected" -Scope "Global" -ErrorAction SilentlyContinue
$hasTestNetCon = Get-Command -Name "Test-NetConnection" -ErrorAction SilentlyContinue
if (-Not $var)
{
if ($hasTestNetCon)
{
$ret = Test-NetConnection -ComputerName 8.8.8.8 -Port 443 -ErrorAction SilentlyContinue -InformationLevel Quiet
}
else
{
$ret = Test-Connection -TargetName 8.8.8.8 -TcpPort 443 -Quiet -ErrorAction SilentlyContinue
}
if (-Not $ret)
{
if ($hasTestNetCon)
{
$ret = Test-NetConnection -ComputerName 1.1.1.1 -Port 443 -ErrorAction SilentlyContinue -InformationLevel Quiet
}
else
{
$ret = Test-Connection -TargetName 1.1.1.1 -TcpPort 443 -Quiet -ErrorAction SilentlyContinue
}
}
if ($ret)
{
$Global:AlyaIsInternetConnected = $ret
}
else
{
$Global:AlyaIsInternetConnected = $false
}
}
return $Global:AlyaIsInternetConnected
}
function Reset-ConsoleWidth()
{
try
{
$pshost = Get-Host
$pswindow = $pshost.UI.RawUI
if ($Global:AlyaConsoleBufferSize)
{
$newsize = $pswindow.BufferSize
if ($newsize)
{
$newsize.width = $Global:AlyaConsoleBufferSize
$pswindow.buffersize = $newsize
}
}
if ($Global:AlyaConsoleWindowsSize)
{
$newsize = $pswindow.windowsize
if ($newsize)
{
$newsize.width = $Global:AlyaConsoleWindowsSize
$pswindow.windowsize = $newsize
}
}
} catch {
Write-Error $_.Exception -ErrorAction Continue
}
}
function Increase-ConsoleWidth(
[int] [Parameter(Mandatory = $false)] $newWidth = 8192)
{
try
{
$pshost = Get-Host
$pswindow = $pshost.UI.RawUI
$newsize = $pswindow.BufferSize
if ($newsize)
{
if (-Not $Global:AlyaConsoleBufferSize -or $Global:AlyaConsoleBufferSize -ne $newWidth)
{
$Global:AlyaConsoleBufferSize = $newsize.width
}
$newsize.width = $newWidth
$pswindow.buffersize = $newsize
}
$newsize = $pswindow.windowsize
if ($newsize)
{
if (-Not $Global:AlyaConsoleWindowsSize -or $Global:AlyaConsoleWindowsSize -ne $newWidth)
{
$Global:AlyaConsoleWindowsSize = $newsize.width
}
$newsize.width = $newWidth
$pswindow.windowsize = $newsize
}
} catch {
Write-Error $_.Exception -ErrorAction Continue
}
}
function Get-Password(
[int] [Parameter(Mandatory = $true)] $length)
{
$allPwdChars = @(
"QWERTYUIOPASDFGHJKLZXCVBNM",
"qwertyuiopasdfghjklzxcvbnm",
"0123456789",
"!@#$%()-_=+"
)
$rnd = [System.Random]::new()
$pwd = ""
for ($n=0; $n -lt $length; $n++)
{
$row = ($n % 4)
$chars = $allPwdChars[$row].ToCharArray()
$pwd += $chars[$rnd.Next(0, $chars.Length - 1)]
}
return $pwd
}
function Wait-UntilProcessEnds(
[string] [Parameter(Mandatory = $true)] $processName)
{
$maxStartTries = 10
$startTried = 0
do
{
$prc = Get-Process -Name $processName -ErrorAction SilentlyContinue
$startTried = $startTried + 1
if ($startTried -gt $maxStartTries)
{
$prc = "Continue"
}
} while (-Not $prc)
do
{
Start-Sleep -Seconds 5
$prc = Get-Process -Name $processName -ErrorAction SilentlyContinue
} while ($prc)
}
<# PACKAGE AND MODULE MANGEMENT FUNCTIONS #>
function Get-PublishedModuleVersion(
[string] [Parameter(Mandatory = $true)] $moduleName,
[Version] $exactVersion = "0.0.0.0",
[bool] $allowPrerelease = $false
)
{
$url = "https://www.powershellgallery.com/packages/$moduleName/?dummy=$(Get-Random)"
$request = [System.Net.WebRequest]::Create($url)
$request.AllowAutoRedirect=$false
[Version]$version = "0.0.0.0"
[string]$fullVersion = "0.0.0.0"
try
{
$response = $request.GetResponse()
$version = $response.GetResponseHeader("Location").Split("/")[-1].Trim()
$fullVersion = $version
$response.Close()
$response.Dispose()
}
catch
{
Write-Warning $_.Exception.Message
return $null
}
if ($allowPrerelease -or $exactVersion -ne "0.0.0.0")
{
if ($exactVersion -ne "0.0.0.0") { $version = $exactVersion }
$url = "https://www.powershellgallery.com/packages/$moduleName/$version/?dummy=$(Get-Random)"
try
{
$response = Invoke-WebRequestIndep -Method "Get" -Uri $url -UseBasicParsing
if ($exactVersion -ne "0.0.0.0")
{
$versionUrl = $response.Links | where { $_.href -like "/packages/$moduleName/$exactVersion*" } | Select-Object -Property href -Last 1 | Out-String
}
else
{
$versionUrl = $response.Links | where { $_.href -like "/packages/$moduleName/*-nightly" } | Select-Object -Property href -Last 1 | Out-String
}
if ($versionUrl)
{
$version = $versionUrl.Split("/")[-1].Replace("-nightly", "").Trim()
$fullVersion = $versionUrl.Split("/")[-1].Trim()
}
else
{
$version = $version
$fullVersion = $fullVersion
}
}
catch
{
Write-Warning $_.Exception.Message
}
}
return @($version, $fullVersion)
}
function Check-Module (
[string] [Parameter(Mandatory = $true)] $moduleName,
[Version] $minimalVersion = "0.0.0.0",
[Version] $exactVersion = "0.0.0.0"
)
{
if ($exactVersion -ne "0.0.0.0")
{
$module = Get-Module -Name $moduleName -ListAvailable | Where-Object { $_.Version -eq $exactVersion }
if (-Not $module)
{
try
{
try
{
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Where-Object { $_.Version -eq $exactVersion }
}
catch
{
Import-Module -Name PowerShellGet
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Where-Object { $_.Version -eq $exactVersion }
}
}
catch { }
}
}
else
{
$module = Get-Module -Name $moduleName -ListAvailable | `
Where-Object { $_.Version -ge $minimalVersion } | Sort-Object -Property Version | Select-Object -Last 1
if (-Not $module)
{
try
{
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | `
Where-Object { $_.Version -ge $minimalVersion } | Sort-Object -Property Version | Select-Object -Last 1
}
catch
{
Import-Module -Name PowerShellGet
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | `
Where-Object { $_.Version -ge $minimalVersion } | Sort-Object -Property Version | Select-Object -Last 1
}
}
}
if (-Not $module)
{
Write-Error "Can't find module $moduleName" -ErrorAction Continue
Write-Error "Please install the module and restart" -ErrorAction Continue
exit
}
}
function DownloadAndInstall-Package($packageName, $nuvrs, $nusrc)
{
$fileName = "$($AlyaTools)\Packages\$packageName_" + $nuvrs + ".nupkg"
Invoke-WebRequest -Uri $nusrc.href -OutFile $fileName
if (-not (Test-Path $fileName))
{
Write-Error " Was not able to download $packageName which is a prerequisite for this script" -ErrorAction Continue
break
}
#Add-Type -AssemblyName System.IO.Compression.FileSystem
#[System.IO.Compression.ZipFile]::ExtractToDirectory($fileName, "$($AlyaTools)\Packages\$packageName")
#New version for mac:
if (-not (Test-Path "$($AlyaTools)\Packages\$packageName"))
{
New-Item -Path "$($AlyaTools)\Packages\$packageName" -ItemType Directory -Force
}
$cmdTst = Get-Command -Name "Expand-Archive" -ParameterName "DestinationPath" -ErrorAction SilentlyContinue
if ($cmdTst)
{
Expand-Archive -Path $fileName -DestinationPath "$($AlyaTools)\Packages\$packageName" -Force
}
else
{
Expand-Archive -Path $fileName -OutputPath "$($AlyaTools)\Packages\$packageName" -Force
}
Remove-Item $fileName
}
function Install-PackageIfNotInstalled (
[string] [Parameter(Mandatory = $true)] $packageName,
[bool] $autoUpdate = $true,
[string] $exactVersion = $null
)
{
if ($AlyaPackageVersionOverwrite.Name -contains $packageName)
{
$exactVersion = ($AlyaPackageVersionOverwrite | Where-Object { $_.name -eq $packageName}).Version
}
if (-Not (Is-InternetConnected))
{
Write-Warning "No internet connection. Not able to check any package!"
return
}
if (-Not (Test-Path "$($AlyaTools)\Packages"))
{
$tmp = New-Item -Path "$($AlyaTools)\Packages" -ItemType Directory -Force
}
if ($exactVersion) {
$resp = Invoke-WebRequestIndep -Uri "https://www.nuget.org/packages/$packageName/$exactVersion" -UseBasicParsing
} else {
$resp = Invoke-WebRequestIndep -Uri "https://www.nuget.org/packages/$packageName" -UseBasicParsing
}
$nusrc = ($resp).Links | Where-Object { $_.href -like "*/package/*" -and $_.outerText -eq "Download package" -or $_.outerText -eq "Manual download" -or $_."data-track" -eq "outbound-manual-download"} | Select-Object -First 1
$nuvrs = $nusrc.href.Substring($nusrc.href.LastIndexOf("/") + 1, $nusrc.href.Length - $nusrc.href.LastIndexOf("/") - 1)
if (-not (Test-Path "$($AlyaTools)\Packages\$packageName\$packageName.nuspec"))
{
Write-Host ('Package {0} is not installed. Installing v{1}' -f $packageName, $nuvrs)
DownloadAndInstall-Package -packageName $packageName -nuvrs $nuvrs -nusrc $nusrc
}
else
{
# Checking package version, updating if required
$nuspec = [xml](Get-Content "$($AlyaTools)\Packages\$packageName\$packageName.nuspec")
$nuvrsInstalled = $nuspec.package.metadata.version
if ($autoUpdate)
{
if ($nuvrsInstalled -ne $nuvrs)
{
$nuvrsInstalled = $nuvrs
Remove-Item -Recurse -Force "$($AlyaTools)\Packages\$packageName"
DownloadAndInstall-Package -packageName $packageName -nuvrs $nuvrs -nusrc $nusrc
}
}
Write-Host ('Package {0} is installed. Used:v{1} Requested:v{2}' -f $packageName, $nuvrsInstalled, $nuvrs)
}
foreach($file in (Get-ChildItem -Path "$($AlyaTools)\Packages\$packageName" -Recurse))
{
Unblock-File -Path $file.FullName
}
}
#Install-PackageIfNotInstalled "Selenium.WebDriver"
#Install-PackageIfNotInstalled "Microsoft.SharePointOnline.CSOM"
function Uninstall-ModuleIfInstalled (
[string] [Parameter(Mandatory = $true)] $moduleName,
[Version] $exactVersion = "0.0.0.0"
)
{
if ($exactVersion -ne "0.0.0.0")
{
$module = Get-Module -Name $moduleName -ListAvailable | Where-Object { $_.Version -eq $exactVersion }
if (-Not $module)
{
try
{
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Where-Object { $_.Version -eq $exactVersion }
}
catch
{
Import-Module -Name PowerShellGet
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Where-Object { $_.Version -eq $exactVersion }
}
}
}
else
{
$module = Get-Module -Name $moduleName -ListAvailable | Sort-Object -Property Version | Select-Object -Last 1
if (-Not $module)
{
try
{
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Sort-Object -Property Version | Select-Object -Last 1
}
catch
{
Import-Module -Name PowerShellGet
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue | Sort-Object -Property Version | Select-Object -Last 1
}
}
}
if ($module)
{
Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue
if ($exactVersion -ne "0.0.0.0")
{
Write-Host ('Uninstalling requested version v{1} from module {0}.' -f $moduleName, $exactVersion)
try {
Uninstall-Module -Name $moduleName -RequiredVersion $exactVersion -Force
}
catch {
$path = Split-Path (Split-Path $module.Path -Parent) -Parent
Remove-Item -Path $path -Recurse -Force
}
}
else
{
Write-Host ('Uninstalling all versions from module {0}.' -f $moduleName)
try {
Uninstall-Module -Name $moduleName -AllVersions -Force
}
catch {
$path = Split-Path (Split-Path $module.Path -Parent) -Parent
Remove-Item -Path $path -Recurse -Force
}
}
}
}
function Install-ModuleIfNotInstalled (
[string] [Parameter(Mandatory = $true)] $moduleName,
[Version] $minimalVersion = "0.0.0.0",
[Version] $exactVersion = "0.0.0.0",
[bool] $autoUpdate = $true,
[bool]$allowPrerelease = $false,
[bool]$doNotLoadModules = $false
)
{
if ($AlyaModuleVersionOverwrite.Name -contains $moduleName)
{
$exactVersion = ($AlyaModuleVersionOverwrite | Where-Object { $_.name -eq $moduleName}).Version
}
if (-Not (Is-InternetConnected))
{
Write-Warning "No internet connection. Not able to check any module!"
return
}
$gmCmd = Get-Command Get-Module
if (-Not $gmCmd)
{
throw "Can't find cmdlt Get-Module"
}
$pkg = Get-Module -Name "PackageManagement" -ListAvailable | Sort-Object -Property Version | Select-Object -Last 1
if ($moduleName -ne "PackageManagement" -and (-Not $pkg -or $pkg.Version -lt [Version]"1.4.7"))
{
Install-ModuleIfNotInstalled "PackageManagement"
throw "PackageManagement updated! Please restart your powershell session"
}
$repCmd = Get-Command Get-PSRepository -ErrorAction SilentlyContinue
if (-Not $repCmd)
{
$ModuleContentUrl = "https://www.powershellgallery.com/api/v2/package/PackageManagement"
do {
try {
$req = Invoke-WebRequest -Uri $ModuleContentUrl -MaximumRedirection 0 -UseBasicParsing -ErrorAction Ignore
}
catch {
$req = $_.Exception.Response
}
$ModuleContentUrl = $req.Headers.Location
} while (!$ModuleContentUrl.Contains(".nupkg"))
$WebClient = New-Object System.Net.WebClient
$PathFolderName = New-Guid
$ModuleContentZip = Join-Path $env:TEMP ("$PathFolderName.zip")
$WebClient.DownloadFile($ModuleContentUrl, $ModuleContentZip)
$ModuleContentDir = Join-Path $env:TEMP $PathFolderName
$cmdTst = Get-Command -Name "Expand-Archive" -ParameterName "DestinationPath" -ErrorAction SilentlyContinue
if ($cmdTst)
{
Expand-Archive -Path $ModuleContentZip -DestinationPath $ModuleContentDir -Force
}
else
{
Expand-Archive -Path $ModuleContentZip -OutputPath $ModuleContentDir -Force
}
if (-Not $doNotLoadModules)
{
Import-Module "$ModuleContentDir\PackageManagement.psd1" -Force -Verbose
}
}
$regRep = Get-PSRepository -Name "PSGallery" -ErrorAction SilentlyContinue
if (-Not $regRep)
{
Register-PSRepository -Name "PSGallery" -SourceLocation "https://www.powershellgallery.com/api/v2/" -PublishLocation "https://www.powershellgallery.com/api/v2/package/" -ScriptSourceLocation "https://www.powershellgallery.com/api/v2/items/psscript/" -ScriptPublishLocation "https://www.powershellgallery.com/api/v2/package/" -InstallationPolicy Trusted -PackageManagementProvider NuGet
}
else
{
if ($regRep.InstallationPolicy -ne "Trusted")
{
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
}
}
$psg = Get-Module -Name PowerShellGet -ListAvailable | Sort-Object -Property Version | Select-Object -Last 1
if ($moduleName -ne "PackageManagement" -and $moduleName -ne "PowerShellGet" -and (-Not $psg -or $psg.Version -lt [Version]"2.0.0.0"))
{
Install-ModuleIfNotInstalled "PowerShellGet"
throw "PowerShellGet updated! Please restart your powershell session"
}