-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathEvergreenAdmx.ps1
2889 lines (2442 loc) · 100 KB
/
EvergreenAdmx.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 -RunAsAdministrator
#region init
<#PSScriptInfo
.VERSION 2411.1
.GUID 999952b7-1337-4018-a1b9-499fad48e734
.AUTHOR Arjan Mensch & Jonathan Pitre
.COMPANYNAME IT-WorXX
.TAGS GroupPolicy GPO Admx Evergreen Automation
.LICENSEURI https://github.com/msfreaks/EvergreenAdmx/blob/main/LICENSE
.PROJECTURI https://github.com/msfreaks/EvergreenAdmx
#>
<#
.SYNOPSIS
Script to automatically download latest Admx files for several products.
.DESCRIPTION
Script to automatically download latest Admx files for several products.
Optionally copies the latest Admx files to a folder of your chosing, for example a Policy Store.
.PARAMETER Windows10Version
The Windows 10 version to get the Admx files for. This value will be ignored if 'Windows 10' is
not specified with -Include parameter.
If the -Include parameter contains 'Windows 10', the latest Windows 10 version will be used.
Defaults to "Windows11Version" if omitted.
Note: Windows 11 23H2 policy definitions now supports Windows 10.
.PARAMETER Windows11Version
The Windows 11 version to get the Admx files for. This value will be ignored if 'Windows 10' is
not specified with -Include parameter.
If omitted, defaults to latest version available .
.PARAMETER WorkingDirectory
Optionally provide a Working Directory for the script.
The script will store Admx files in a subdirectory called "admx".
The script will store downloaded files in a subdirectory called "downloads".
If omitted the script will treat the script's folder as the working directory.
.PARAMETER PolicyStore
Optionally provide a Policy Store location to copy the Admx files to after processing.
.PARAMETER Languages
Optionally provide an array of languages to process. Entries must be in 'xy-XY' format.
If omitted the script will default to 'en-US'.
.PARAMETER UseProductFolders
When specified the extracted Admx files are copied to their respective product folders in a subfolder of 'Admx' in the WorkingDirectory.
.PARAMETER CustomPolicyStore
When specified processes a location for custom policy files. Can be UNC format or local folder.
The script will expect to find .admx files in this location, and at least one language folder holding the .adml file(s).
Versioning will be done based on the newest file found recursively in this location (any .admx or .adml).
Note that if any file has changed the script will process all files found in location.
.PARAMETER Include
Array containing Admx products to include when checking for updates.
Defaults to "Windows 11", "Microsoft Edge", "Microsoft OneDrive", "Microsoft Office" if omitted.
.PARAMETER PreferLocalOneDrive
Microsoft OneDrive Admx files are only available after installing OneDrive.
If this script is running on a machine that has OneDrive installed, this switch will prevent automatic uninstallation of OneDrive.
.EXAMPLE
.\EvergreenAdmx.ps1 -PolicyStore "C:\Windows\SYSVOL\domain\Policies\PolicyDefinitions" -Languages @("en-US", "nl-NL") -UseProductFolders
Get policy default set of products, storing results in product folders, for both en-us and nl-NL languages, and copies the files to the Policy store.
.LINK
https://github.com/msfreaks/EvergreenAdmx
https://msfreaks.wordpress.com
#>
[CmdletBinding(DefaultParameterSetName = 'Windows11Version')]
param(
[Parameter(Mandatory = $False, ParameterSetName = "Windows10Version", Position = 0)][ValidateSet("1903", "1909", "2004", "20H2", "21H1", "21H2", "22H2")]
[System.String] $Windows10Version = "22H2",
[Parameter(Mandatory = $False, ParameterSetName = "Windows11Version", Position = 0)][ValidateSet("21H2", "22H2", "23H2", "24H2")]
[Alias("WindowsVersion")]
[System.String] $Windows11Version = "24H2",
[Parameter(Mandatory = $False)]
[System.String] $WorkingDirectory = $null,
[Parameter(Mandatory = $False)]
[System.String] $PolicyStore = $null,
[Parameter(Mandatory = $False)]
[System.String[]] $Languages = @("en-US"),
[Parameter(Mandatory = $False)]
[switch] $UseProductFolders,
[Parameter(Mandatory = $False)]
[System.String] $CustomPolicyStore = $null,
[Parameter(Mandatory = $False)][ValidateSet("Custom Policy Store", "Windows 10", "Windows 11", "Microsoft Edge", "Microsoft OneDrive", "Microsoft Office", "FSLogix", "Adobe Acrobat", "Adobe Reader", "BIS-F", "Citrix Workspace App", "Google Chrome", "Microsoft Desktop Optimization Pack", "Mozilla Firefox", "Zoom Desktop Client", "Azure Virtual Desktop", "Microsoft Winget")]
[System.String[]] $Include = @("Windows 11", "Microsoft Edge", "Microsoft OneDrive", "Microsoft Office"),
[Parameter(Mandatory = $False)]
[switch] $PreferLocalOneDrive = $False
)
$ProgressPreference = "SilentlyContinue"
$ErrorActionPreference = "SilentlyContinue"
$admxversions = $null
if (-not $WorkingDirectory) { $WorkingDirectory = $PSScriptRoot }
if (Test-Path -Path "$($WorkingDirectory)\admxversions.xml") { $admxversions = Import-Clixml -Path "$($WorkingDirectory)\admxversions.xml" }
if (-not (Test-Path -Path "$($WorkingDirectory)\admx")) { $null = New-Item -Path "$($WorkingDirectory)\admx" -ItemType Directory -Force }
if (-not (Test-Path -Path "$($WorkingDirectory)\downloads")) { $null = New-Item -Path "$($WorkingDirectory)\downloads" -ItemType Directory -Force }
if ($PolicyStore -and -not $PolicyStore.EndsWith("\")) { $PolicyStore += "\" }
if ($Languages -notmatch "([A-Za-z]{2})-([A-Za-z]{2})$") { Write-Warning "Language not in expected format: $($Languages -notmatch "([A-Za-z]{2})-([A-Za-z]{2})$")" }
if ($CustomPolicyStore -and -not (Test-Path -Path "$($CustomPolicyStore)")) { throw "'$($CustomPolicyStore)' is not a valid path." }
if ($CustomPolicyStore -and -not $CustomPolicyStore.EndsWith("\")) { $CustomPolicyStore += "\" }
if ($CustomPolicyStore -and (Get-ChildItem -Path $CustomPolicyStore -Directory) -notmatch "([A-Za-z]{2})-([A-Za-z]{2})$") { throw "'$($CustomPolicyStore)' does not contain at least one subfolder matching the language format (e.g 'en-US')." }
if ($PreferLocalOneDrive -and $Include -notcontains "Microsoft OneDrive") { Write-Warning "PreferLocalOneDrive is used, but Microsoft OneDrive is not in the list of included products to process." }
$oneDriveADMXFolder = $null
if ((Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\OneDrive").CurrentVersionPath)
{
$oneDriveADMXFolder = (Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Microsoft\OneDrive").CurrentVersionPath
}
if ((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\OneDrive").CurrentVersionPath)
{
$oneDriveADMXFolder = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\OneDrive").CurrentVersionPath
}
if ($PreferLocalOneDrive -and $Include -contains "Microsoft OneDrive" -and $null -eq $oneDriveADMXFolder)
{
throw "PreferLocalOneDrive will only work if OneDrive is machine installed. User installed OneDrive is not supported.`nLocal machine installed OneDrive not found."
break
}
Write-Verbose "Windows 10 Version:`t'$($Windows10Version)'"
Write-Verbose "Windows 11 Version:`t'$($Windows11Version)'"
Write-Verbose "WorkingDirectory:`t`t'$($WorkingDirectory)'"
Write-Verbose "PolicyStore:`t`t`t'$($PolicyStore)'"
Write-Verbose "CustomPolicyStore:`t`t'$($CustomPolicyStore)'"
Write-Verbose "Languages:`t`t`t`t'$($Languages)'"
Write-Verbose "Use product folders:`t'$($UseProductFolders)'"
Write-Verbose "Admx path:`t`t`t`t'$($WorkingDirectory)\admx'"
Write-Verbose "Download path:`t`t`t'$($WorkingDirectory)\downloads'"
Write-Verbose "Included:`t`t`t`t'$($Include -join ', ')'"
Write-Verbose "PreferLocalOneDrive:`t'$($PreferLocalOneDrive)'"
#endregion
#region functions
function Get-Link
{
<#
.SYNOPSIS
Returns a specific link from a web page.
.DESCRIPTION
Returns a specific link from a web page.
.NOTES
Site: https://packageology.com
Author: Dan Gough
Twitter: @packageologist
.LINK
https://github.com/DanGough/Nevergreen
.PARAMETER Uri
The URI to query.
.PARAMETER MatchProperty
Which property the RegEx pattern should be applied to, e.g. href, outerHTML, class, title.
.PARAMETER Pattern
The RegEx pattern to apply to the selected property. Supply an array of patterns to receive multiple links.
.PARAMETER ReturnProperty
Optional. Specifies which property to return from the link. Defaults to href, but 'data-filename' can also be useful to retrieve.
.PARAMETER UserAgent
Optional parameter to provide a user agent for Invoke-WebRequest to use. Examples are:
Googlebot: 'Googlebot/2.1 (+http://www.google.com/bot.html)'
Microsoft Edge: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
.EXAMPLE
Get-Link -Uri 'http://somewhere.com' -MatchProperty href -Pattern '\.exe$'
Description:
Returns first download link matching *.exe from http://somewhere.com.
#>
[CmdletBinding(SupportsShouldProcess = $False)]
param (
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline)]
[ValidatePattern('^(http|https)://')]
[Alias('Url')]
[String] $Uri,
[Parameter(
Mandatory = $true,
Position = 1)]
[ValidateNotNullOrEmpty()]
#[ValidateSet('href', 'outerHTML', 'innerHTML', 'outerText', 'innerText', 'class', 'title', 'tagName', 'data-filename')]
[String] $MatchProperty,
[Parameter(
Mandatory = $true,
Position = 2)]
[ValidateNotNullOrEmpty()]
[String[]] $Pattern,
[Parameter(
Mandatory = $false,
Position = 3)]
[ValidateNotNullOrEmpty()]
[String] $ReturnProperty = 'href',
[Parameter(
Mandatory = $false)]
[String] $UserAgent,
[System.Collections.Hashtable] $Headers,
[Switch] $PrefixDomain,
[Switch] $PrefixParent
)
$ProgressPreference = 'SilentlyContinue'
$ParamHash = @{
Uri = $Uri
Method = 'GET'
UseBasicParsing = $True
DisableKeepAlive = $True
ErrorAction = 'Stop'
}
if ($UserAgent)
{
$ParamHash.UserAgent = $UserAgent
}
if ($Headers)
{
$ParamHash.Headers = $Headers
}
try
{
$Response = Invoke-WebRequest @ParamHash
foreach ($CurrentPattern in $Pattern)
{
$Link = $Response.Links | Where-Object $MatchProperty -Match $CurrentPattern | Select-Object -First 1 -ExpandProperty $ReturnProperty
if ($PrefixDomain)
{
$BaseURL = ($Uri -split '/' | Select-Object -First 3) -join '/'
$Link = Set-UriPrefix -Uri $Link -Prefix $BaseURL
}
elseif ($PrefixParent)
{
$BaseURL = ($Uri -split '/' | Select-Object -SkipLast 1) -join '/'
$Link = Set-UriPrefix -Uri $Link -Prefix $BaseURL
}
$Link
}
}
catch
{
Write-Error "$($MyInvocation.MyCommand): $($_.Exception.Message)"
}
}
function Get-Version
{
<#
.SYNOPSIS
Extracts a version number from either a string or the content of a web page using a chosen or pre-defined match pattern.
.DESCRIPTION
Extracts a version number from either a string or the content of a web page using a chosen or pre-defined match pattern.
.NOTES
Site: https://packageology.com
Author: Dan Gough
Twitter: @packageologist
.LINK
https://github.com/DanGough/Nevergreen
.PARAMETER String
The string to process.
.PARAMETER Uri
The Uri to load web content from to process.
.PARAMETER UserAgent
Optional parameter to provide a user agent for Invoke-WebRequest to use. Examples are:
Googlebot: 'Googlebot/2.1 (+http://www.google.com/bot.html)'
Microsoft Edge: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
.PARAMETER Pattern
Optional RegEx pattern to use for version matching. Pattern to return must be included in parentheses.
.PARAMETER ReplaceWithDot
Switch to automatically replace characters - or _ with . in detected version.
.EXAMPLE
Get-Version -String 'http://somewhere.com/somefile_1.2.3.exe'
Description:
Returns '1.2.3'
#>
[CmdletBinding(SupportsShouldProcess = $False)]
param (
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ParameterSetName = 'String')]
[ValidateNotNullOrEmpty()]
[String[]] $String,
[Parameter(
Mandatory = $true,
ParameterSetName = 'Uri')]
[ValidatePattern('^(http|https)://')]
[String] $Uri,
[Parameter(
Mandatory = $false,
ParameterSetName = 'Uri')]
[String] $UserAgent,
[Parameter(
Mandatory = $false,
Position = 1)]
[ValidateNotNullOrEmpty()]
[String] $Pattern = '((?:\d+\.)+\d+)',
[Switch] $ReplaceWithDot
)
begin
{
}
process
{
if ($PsCmdlet.ParameterSetName -eq 'Uri')
{
$ProgressPreference = 'SilentlyContinue'
try
{
$ParamHash = @{
Uri = $Uri
Method = 'GET'
UseBasicParsing = $True
DisableKeepAlive = $True
ErrorAction = 'Stop'
}
if ($UserAgent)
{
$ParamHash.UserAgent = $UserAgent
}
$String = (Invoke-WebRequest @ParamHash).Content
}
catch
{
Write-Error "Unable to query URL '$Uri': $($_.Exception.Message)"
}
}
foreach ($CurrentString in $String)
{
if ($ReplaceWithDot)
{
$CurrentString = $CurrentString.Replace('-', '.').Replace('+', '.').Replace('_', '.')
}
if ($CurrentString -match $Pattern)
{
$matches[1]
}
else
{
Write-Warning "No version found within $CurrentString using pattern $Pattern"
}
}
}
end
{
}
}
# Replace Get-RedirectedUrl function
function Resolve-Uri
{
<#
.SYNOPSIS
Resolves a URI and also returns the filename and last modified date if found.
.DESCRIPTION
Resolves a URI and also returns the filename and last modified date if found.
.NOTES
Site: https://packageology.com
Author: Dan Gough
Twitter: @packageologist
.LINK
https://github.com/DanGough/Nevergreen
.PARAMETER Uri
The URI resolve. Accepts an array of strings or pipeline input.
.PARAMETER UserAgent
Optional parameter to provide a user agent for Invoke-WebRequest to use. Examples are:
Googlebot: 'Googlebot/2.1 (+http://www.google.com/bot.html)'
Microsoft Edge: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
.EXAMPLE
Resolve-Uri -Uri 'http://somewhere.com/somefile.exe'
Description:
Returns the absolute redirected URI, filename and last modified date.
#>
[CmdletBinding(SupportsShouldProcess = $False)]
param (
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[ValidatePattern('^(http|https)://')]
[Alias('Url')]
[String[]] $Uri,
[Parameter(
Mandatory = $false,
Position = 1)]
[String] $UserAgent,
[System.Collections.Hashtable] $Headers
)
begin
{
$ProgressPreference = 'SilentlyContinue'
}
process
{
foreach ($UriToResolve in $Uri)
{
try
{
$ParamHash = @{
Uri = $UriToResolve
Method = 'Head'
UseBasicParsing = $True
DisableKeepAlive = $True
ErrorAction = 'Stop'
}
if ($UserAgent)
{
$ParamHash.UserAgent = $UserAgent
}
if ($Headers)
{
$ParamHash.Headers = $Headers
}
$Response = Invoke-WebRequest @ParamHash
if ($IsCoreCLR)
{
$ResolvedUri = $Response.BaseResponse.RequestMessage.RequestUri.AbsoluteUri
}
else
{
$ResolvedUri = $Response.BaseResponse.ResponseUri.AbsoluteUri
}
Write-Verbose "$($MyInvocation.MyCommand): URI resolved to: $ResolvedUri"
#PowerShell 7 returns each header value as single unit arrays instead of strings which messes with the -match operator coming up, so use Select-Object:
$ContentDisposition = $Response.Headers.'Content-Disposition' | Select-Object -First 1
if ($ContentDisposition -match 'filename="?([^\\/:\*\?"<>\|]+)')
{
$FileName = $matches[1]
Write-Verbose "$($MyInvocation.MyCommand): Content-Disposition header found: $ContentDisposition"
Write-Verbose "$($MyInvocation.MyCommand): File name determined from Content-Disposition header: $FileName"
}
else
{
$Slug = [uri]::UnescapeDataString($ResolvedUri.Split('?')[0].Split('/')[-1])
if ($Slug -match '^[^\\/:\*\?"<>\|]+\.[^\\/:\*\?"<>\|]+$')
{
Write-Verbose "$($MyInvocation.MyCommand): URI slug is a valid file name: $FileName"
$FileName = $Slug
}
else
{
$FileName = $null
}
}
try
{
$LastModified = [DateTime]($Response.Headers.'Last-Modified' | Select-Object -First 1)
Write-Verbose "$($MyInvocation.MyCommand): Last modified date: $LastModified"
}
catch
{
Write-Verbose "$($MyInvocation.MyCommand): Unable to parse date from last modified header: $($Response.Headers.'Last-Modified')"
$LastModified = $null
}
}
catch
{
Throw "$($MyInvocation.MyCommand): Unable to resolve URI: $($_.Exception.Message)"
}
if ($ResolvedUri)
{
[PSCustomObject]@{
Uri = $ResolvedUri
FileName = $FileName
LastModified = $LastModified
}
}
}
}
end
{
}
}
# Replace Invoke-WebRequest (FASTER DOWNLOADS!)
function Invoke-Download
{
[CmdletBinding()]
param(
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[Alias('URI')]
[ValidateNotNullOrEmpty()]
[string]$URL,
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string]$Destination = $PWD.Path,
[Parameter(Position = 2)]
[string]$FileName,
[string[]]$UserAgent = @('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36', 'Googlebot/2.1 (+http://www.google.com/bot.html)'),
[string]$TempPath = [System.IO.Path]::GetTempPath(),
[switch]$IgnoreDate,
[switch]$BlockFile,
[switch]$NoClobber,
[switch]$NoProgress,
[switch]$PassThru
)
begin
{
# Required on Windows Powershell only
if ($PSEdition -eq 'Desktop')
{
Add-Type -AssemblyName System.Net.Http
Add-Type -AssemblyName System.Web
}
# Enable TLS 1.2 in addition to whatever is pre-configured
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
# Create one single client object for the pipeline
$HttpClient = New-Object System.Net.Http.HttpClient
}
process
{
Write-Verbose "Requesting headers from URL '$URL'"
foreach ($UserAgentString in $UserAgent)
{
$HttpClient.DefaultRequestHeaders.Remove('User-Agent') | Out-Null
if ($UserAgentString)
{
Write-Verbose "Using UserAgent '$UserAgentString'"
$HttpClient.DefaultRequestHeaders.Add('User-Agent', $UserAgentString)
}
# This sends a GET request but only retrieves the headers
$ResponseHeader = $HttpClient.GetAsync($URL, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).Result
# Exit the foreach if success
if ($ResponseHeader.IsSuccessStatusCode)
{
break
}
}
if ($ResponseHeader.IsSuccessStatusCode)
{
Write-Verbose 'Successfully retrieved headers'
if ($ResponseHeader.RequestMessage.RequestUri.AbsoluteUri -ne $URL)
{
Write-Verbose "URL '$URL' redirects to '$($ResponseHeader.RequestMessage.RequestUri.AbsoluteUri)'"
}
try
{
$FileSize = $null
$FileSize = [int]$ResponseHeader.Content.Headers.GetValues('Content-Length')[0]
$FileSizeReadable = switch ($FileSize)
{
{ $_ -gt 1TB } { '{0:n2} TB' -f ($_ / 1TB); Break }
{ $_ -gt 1GB } { '{0:n2} GB' -f ($_ / 1GB); Break }
{ $_ -gt 1MB } { '{0:n2} MB' -f ($_ / 1MB); Break }
{ $_ -gt 1KB } { '{0:n2} KB' -f ($_ / 1KB); Break }
default { '{0} B' -f $_ }
}
Write-Verbose "File size: $FileSize bytes ($FileSizeReadable)"
}
catch
{
Write-Verbose 'Unable to determine file size'
}
# Try to get the last modified date from the "Last-Modified" header, use error handling in case string is in invalid format
try
{
$LastModified = $null
$LastModified = [DateTime]::ParseExact($ResponseHeader.Content.Headers.GetValues('Last-Modified')[0], 'r', [System.Globalization.CultureInfo]::InvariantCulture)
Write-Verbose "Last modified: $($LastModified.ToString())"
}
catch
{
Write-Verbose 'Last-Modified header not found'
}
if ($FileName)
{
$FileName = $FileName.Trim()
Write-Verbose "Will use supplied filename '$FileName'"
}
else
{
# Get the file name from the "Content-Disposition" header if available
try
{
$ContentDispositionHeader = $null
$ContentDispositionHeader = $ResponseHeader.Content.Headers.GetValues('Content-Disposition')[0]
Write-Verbose "Content-Disposition header found: $ContentDispositionHeader"
}
catch
{
Write-Verbose 'Content-Disposition header not found'
}
if ($ContentDispositionHeader)
{
$ContentDispositionRegEx = @'
^.*filename\*?\s*=\s*"?(?:UTF-8|iso-8859-1)?(?:'[^']*?')?([^";]+)
'@
if ($ContentDispositionHeader -match $ContentDispositionRegEx)
{
# GetFileName ensures we are not getting a full path with slashes. UrlDecode will convert characters like %20 back to spaces.
$FileName = [System.IO.Path]::GetFileName([System.Web.HttpUtility]::UrlDecode($matches[1]))
# If any further invalid filename characters are found, convert them to spaces.
[IO.Path]::GetinvalidFileNameChars() | ForEach-Object { $FileName = $FileName.Replace($_, ' ') }
$FileName = $FileName.Trim()
Write-Verbose "Extracted filename '$FileName' from Content-Disposition header"
}
else
{
Write-Verbose 'Failed to extract filename from Content-Disposition header'
}
}
if ([string]::IsNullOrEmpty($FileName))
{
# If failed to parse Content-Disposition header or if it's not available, extract the file name from the absolute URL to capture any redirections.
# GetFileName ensures we are not getting a full path with slashes. UrlDecode will convert characters like %20 back to spaces. The URL is split with ? to ensure we can strip off any API parameters.
$FileName = [System.IO.Path]::GetFileName([System.Web.HttpUtility]::UrlDecode($ResponseHeader.RequestMessage.RequestUri.AbsoluteUri.Split('?')[0]))
[IO.Path]::GetinvalidFileNameChars() | ForEach-Object { $FileName = $FileName.Replace($_, ' ') }
$FileName = $FileName.Trim()
Write-Verbose "Extracted filename '$FileName' from absolute URL '$($ResponseHeader.RequestMessage.RequestUri.AbsoluteUri)'"
}
}
}
else
{
Write-Verbose 'Failed to retrieve headers'
}
if ([string]::IsNullOrEmpty($FileName))
{
# If still no filename set, extract the file name from the original URL.
# GetFileName ensures we are not getting a full path with slashes. UrlDecode will convert characters like %20 back to spaces. The URL is split with ? to ensure we can strip off any API parameters.
$FileName = [System.IO.Path]::GetFileName([System.Web.HttpUtility]::UrlDecode($URL.Split('?')[0]))
[System.IO.Path]::GetInvalidFileNameChars() | ForEach-Object { $FileName = $FileName.Replace($_, ' ') }
$FileName = $FileName.Trim()
Write-Verbose "Extracted filename '$FileName' from original URL '$URL'"
}
$DestinationFilePath = Join-Path $Destination $FileName
# Exit if -NoClobber specified and file exists.
if ($NoClobber -and (Test-Path -LiteralPath $DestinationFilePath -PathType Leaf))
{
Write-Error 'NoClobber switch specified and file already exists'
return
}
# Open the HTTP stream
$ResponseStream = $HttpClient.GetStreamAsync($URL).Result
if ($ResponseStream.CanRead)
{
# Check TempPath exists and create it if not
if (-not (Test-Path -LiteralPath $TempPath -PathType Container))
{
Write-Verbose "Temp folder '$TempPath' does not exist"
try
{
New-Item -Path $Destination -ItemType Directory -Force | Out-Null
Write-Verbose "Created temp folder '$TempPath'"
}
catch
{
Write-Error "Unable to create temp folder '$TempPath': $_"
return
}
}
# Generate temp file name
$TempFileName = (New-Guid).ToString('N') + ".tmp"
$TempFilePath = Join-Path $TempPath $TempFileName
# Check Destiation exists and create it if not
if (-not (Test-Path -LiteralPath $Destination -PathType Container))
{
Write-Verbose "Output folder '$Destination' does not exist"
try
{
New-Item -Path $Destination -ItemType Directory -Force | Out-Null
Write-Verbose "Created output folder '$Destination'"
}
catch
{
Write-Error "Unable to create output folder '$Destination': $_"
return
}
}
# Open file stream
try
{
$FileStream = [System.IO.File]::Create($TempFilePath)
}
catch
{
Write-Error "Unable to create file '$TempFilePath': $_"
return
}
if ($FileStream.CanWrite)
{
Write-Verbose "Downloading to temp file '$TempFilePath'..."
$Buffer = New-Object byte[] 64KB
$BytesDownloaded = 0
$ProgressIntervalMs = 250
$ProgressTimer = (Get-Date).AddMilliseconds(-$ProgressIntervalMs)
while ($true)
{
try
{
# Read stream into buffer
$ReadBytes = $ResponseStream.Read($Buffer, 0, $Buffer.Length)
# Track bytes downloaded and display progress bar if enabled and file size is known
$BytesDownloaded += $ReadBytes
if (!$NoProgress -and (Get-Date) -gt $ProgressTimer.AddMilliseconds($ProgressIntervalMs))
{
if ($FileSize)
{
$PercentComplete = [System.Math]::Floor($BytesDownloaded / $FileSize * 100)
Write-Progress -Activity "Downloading $FileName" -Status "$BytesDownloaded of $FileSize bytes ($PercentComplete%)" -PercentComplete $PercentComplete
}
else
{
Write-Progress -Activity "Downloading $FileName" -Status "$BytesDownloaded of ? bytes" -PercentComplete 0
}
$ProgressTimer = Get-Date
}
# If end of stream
if ($ReadBytes -eq 0)
{
Write-Progress -Activity "Downloading $FileName" -Completed
$FileStream.Close()
$FileStream.Dispose()
try
{
Write-Verbose "Moving temp file to destination '$DestinationFilePath'"
$DownloadedFile = Move-Item -LiteralPath $TempFilePath -Destination $DestinationFilePath -Force -PassThru
}
catch
{
Write-Error "Error moving file from '$TempFilePath' to '$DestinationFilePath': $_"
return
}
if ($IsWindows)
{
if ($BlockFile)
{
Write-Verbose 'Marking file as downloaded from the internet'
Set-Content -LiteralPath $DownloadedFile -Stream 'Zone.Identifier' -Value "[ZoneTransfer]`nZoneId=3"
}
else
{
Unblock-File -LiteralPath $DownloadedFile
}
}
if ($LastModified -and -not $IgnoreDate)
{
Write-Verbose 'Setting Last Modified date'
$DownloadedFile.LastWriteTime = $LastModified
}
Write-Verbose 'Download complete!'
if ($PassThru)
{
$DownloadedFile
}
break
}
$FileStream.Write($Buffer, 0, $ReadBytes)
}
catch
{
Write-Error "Error downloading file: $_"
Write-Progress -Activity "Downloading $FileName" -Completed
$FileStream.Close()
$FileStream.Dispose()
break
}
}
}
}
else
{
Write-Error 'Failed to start download'
}
# Reset this to avoid reusing the same name when fed multiple URLs via the pipeline
$FileName = $null
}
end
{
$HttpClient.Dispose()
}
}
function Copy-Admx
{
param (
[string]$SourceFolder,
[string]$TargetFolder,
[string]$PolicyStore = $null,
[string]$ProductName,
[switch]$Quiet,
[string[]]$Languages = $null
)
if (-not (Test-Path -Path "$($TargetFolder)")) { $null = (New-Item -Path "$($TargetFolder)" -ItemType Directory -Force) }
if (-not $Languages -or $Languages -eq "") { $Languages = @('en-US') }
Write-Verbose "Copying Admx files from '$($SourceFolder)' to '$($TargetFolder)'"
Copy-Item -Path "$($SourceFolder)\*.admx" -Destination "$($TargetFolder)" -Force
foreach ($language in $Languages)
{
if (-not (Test-Path -Path "$($SourceFolder)\$($language)"))
{
Write-Verbose "$($language) not found"
if (-not $Quiet) { Write-Warning "Language '$($language)' not found for '$($ProductName)'. Processing 'en-US' instead." }
$language = "en-US"
}
if (-not (Test-Path -Path "$($TargetFolder)\$($language)"))
{
Write-Verbose "'$($TargetFolder)\$($language)' does not exist, creating folder"
$null = (New-Item -Path "$($TargetFolder)\$($language)" -ItemType Directory -Force)
}
Write-Verbose "Copying '$($SourceFolder)\$($language)\*.adml' to '$($TargetFolder)\$($language)'"
Copy-Item -Path "$($SourceFolder)\$($language)\*.adml" -Destination "$($TargetFolder)\$($language)" -Force
}
if ($PolicyStore)
{
Write-Verbose "Copying Admx files from '$($SourceFolder)' to '$($PolicyStore)'"
Copy-Item -Path "$($SourceFolder)\*.admx" -Destination "$($PolicyStore)" -Force
foreach ($language in $Languages)
{
if (-not (Test-Path -Path "$($SourceFolder)\$($language)")) { $language = "en-US" }
if (-not (Test-Path -Path "$($PolicyStore)$($language)")) { $null = (New-Item -Path "$($PolicyStore)$($language)" -ItemType Directory -Force) }
Copy-Item -Path "$($SourceFolder)\$($language)\*.adml" -Destination "$($PolicyStore)$($language)" -Force
}
}
}
function Get-FSLogixOnline
{
<#
.SYNOPSIS
Returns latest Version and Uri for FSLogix
#>
try
{
# grab URI (redirected url)
$URL = 'https://aka.ms/fslogix/download'
$URI = (Resolve-Uri -Uri $URL).URI
# grab version
$Version = Get-Version -String $URI -Pattern "(\d+(\.\d+){1,4})"
# return evergreen object
return @{ Version = $Version; URI = $URI }
}
catch
{
Throw $_
}
}
function Get-MicrosoftOfficeAdmxOnline
{
<#
.SYNOPSIS
Returns latest Version and Uri for the Office Admx files (both x64 and x86)
#>
$id = "49030"
$urlVersion = "https://www.microsoft.com/en-us/download/details.aspx?id=$($id)"
$urlDownload = "https://www.microsoft.com/en-us/download/confirmation.aspx?id=$($id)"
try
{
# load page for version scrape
$web = (Invoke-WebRequest -UseDefaultCredentials -UseBasicParsing -Uri $urlVersion -MaximumRedirection 0 -UserAgent 'Googlebot/2.1 (+http://www.google.com/bot.html)').RawContent
# grab version
$regEx = '(version\":")((?:\d+\.)+(?:\d+))"'
$version = ($web | Select-String -Pattern $regEx).Matches.Groups[2].Value
# load page for uri scrape
$web = Invoke-WebRequest -UseDefaultCredentials -UseBasicParsing -Uri $urlDownload -MaximumRedirection 0 -UserAgent 'Googlebot/2.1 (+http://www.google.com/bot.html)'
# grab x64 version
$hrefx64 = $web.Links | Where-Object { $_.outerHTML -like "*click here to download manually*" -and $_.href -like "*.exe" -and $_.href -like "*x64*" } | Select-Object -First 1
# grab x86 version
$hrefx86 = $web.Links | Where-Object { $_.outerHTML -like "*click here to download manually*" -and $_.href -like "*.exe" -and $_.href -like "*x86*" } | Select-Object -First 1
# return evergreen object
return @( @{ Version = $version; URI = $hrefx64.href; Architecture = "x64" }, @{ Version = $version; URI = $hrefx86.href; Architecture = "x86" })
}
catch
{
Throw $_
}
}
function Get-WindowsAdmxDownloadId
{
<#
.SYNOPSIS
Returns Windows admx download Id
.PARAMETER WindowsEdition
Specifies Windows edition (Example: 11)