Public/Get-DownOSDBuilder.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
<#
.SYNOPSIS
Downloads Microsoft Updates for use in OSDBuilder
 
.DESCRIPTION
Downloads Microsoft Updates for use in OSDBuilder
 
.LINK
https://osdbuilder.osdeploy.com/module/functions/get-downosdbuilder
#>

function Get-DownOSDBuilder {
    [CmdletBinding(DefaultParameterSetName='OSDUpdate')]
    Param (

        #Download OneDrive Sync Client
        [Parameter(ParameterSetName='Content')]
        [ValidateSet(
            'OneDriveSetup Production',
            'OneDriveSetup Enterprise')]
        [string]$ContentDownload,
        
        #Download the selected Microsoft Updates
        #By default, updates are not downloaded
        [Parameter(ParameterSetName='OSDUpdate')]
        [switch]$Download,

        #Skip Feature Updates GridView
        #Be careful as this will automatically download
        [Parameter(ParameterSetName='FeatureUpdates')]
        [switch]$SkipGridView,

        #Downloads Feature Updates
        [Parameter(ParameterSetName='FeatureUpdates',Mandatory = $True)]
        [switch]$FeatureUpdates,

        #Feature Update Architecture
        [Parameter(ParameterSetName = 'FeatureUpdates')]
        [ValidateSet ('x64','x86')]
        [string]$FeatureArch,

        #Feature Update Build
        [Parameter(ParameterSetName = 'FeatureUpdates')]
        [ValidateSet (1809,1903,1909,2004,2009)]
        [string]$FeatureBuild,

        #Feature Update Edition
        [Parameter(ParameterSetName = 'FeatureUpdates')]
        [ValidateSet ('Business','Consumer')]
        [string]$FeatureEdition,

        #Feature Update Language
        [Parameter(ParameterSetName = 'FeatureUpdates')]
        [ValidateSet (
            'ar-sa','bg-bg','cs-cz','da-dk','de-de','el-gr',
            'en-gb','en-us','es-es','es-mx','et-ee','fi-fi',
            'fr-ca','fr-fr','he-il','hr-hr','hu-hu','it-it',
            'ja-jp','ko-kr','lt-lt','lv-lv','nb-no','nl-nl',
            'pl-pl','pt-br','pt-pt','ro-ro','ru-ru','sk-sk',
            'sl-si','sr-latn-rs','sv-se','th-th','tr-tr',
            'uk-ua','zh-cn','zh-tw'
        )]
        [string[]]$FeatureLang,

        #Display the results in a GridView with PassThru enabled
        [Parameter(ParameterSetName='OSDUpdate')]
        [switch]$GridView,
        
        #Remove Superseded Updates that are no longer needed
        [Parameter(ParameterSetName = 'OSDUpdateSuperseded', Mandatory = $True)]
        [ValidateSet ('List','Remove')]
        [string]$Superseded,

        #Filter Microsoft Updates for a specific OS Architecture
        [Parameter(ParameterSetName = 'OSDUpdate')]
        [ValidateSet ('x64','x86')]
        [string]$UpdateArch,

        #Filter Microsoft Updates for a specific ReleaseId
        [Parameter(ParameterSetName='OSDUpdate')]
        [ValidateSet (2009,2004,1909,1903,1809,1803,1709,1703,1607,1511,1507,7601,7603)]
        [Alias('ReleaseId')]
        [string]$UpdateBuild,

        #Filter Microsoft Updates for a specific Update type
        [Parameter(ParameterSetName='OSDUpdate')]
        [ValidateSet(
            'SSU Servicing Stack Update',
            'LCU Latest Cumulative Update',
            'DUSU Setup Dynamic Update',
            'DUCU Component Dynamic Update',
            'Adobe Flash Player',
            'DotNet Framework',
            'Optional')]
        [string]$UpdateGroup,
        
        #Filter Microsoft Updates for a specific OS
        [Parameter(ParameterSetName='OSDUpdate')]
        [ValidateSet(
            'Windows 7',
            'Windows 10',
            'Windows Server 2012 R2',
            'Windows Server 2016',
            'Windows Server 2019',
            'Windows Server')]
        [string]$UpdateOS,

        #Download updates using Webclient instead of BITS
        [Parameter(ParameterSetName='OSDUpdate')]
        [switch]$WebClient,

        [Parameter(ParameterSetName='OSDUpdate')]
        [switch]$CheckFileHash

    )

    Begin {
        #===================================================================================================
        # Get-OSDBuilder
        #===================================================================================================
        Get-OSDBuilder -CreatePaths -HideDetails
        #===================================================================================================
        # Get-OSDGather -Property IsAdmin
        #===================================================================================================
        if ((Get-OSDGather -Property IsAdmin) -eq $false) {
            Write-Warning 'OSDBuilder: This function needs to be run as Administrator'
            Pause
            Break
        }
    }

    PROCESS {
        #Write-Host '========================================================================================' -ForegroundColor DarkGray
        #Write-Host -ForegroundColor Green "$($MyInvocation.MyCommand.Name) PROCESS"

        #===================================================================================================
        # FeatureUpdates
        #===================================================================================================
        if ($FeatureUpdates.IsPresent) {
            Write-Warning "FeatureUpdates are downloaded using BITS Transfer"
            Write-Warning "Windows Server 2016 (1607) does not support decompressing ESD Files"
            #===================================================================================================
            # Get FeatureUpdateDownloads
            #===================================================================================================
            $FeatureUpdateDownloads = @()
            $FeatureUpdateDownloads = Get-FeatureUpdateDownloads
            #===================================================================================================
            # Filters
            #===================================================================================================
            if ($FeatureArch) {$FeatureUpdateDownloads = $FeatureUpdateDownloads | Where-Object {$_.UpdateArch -eq $FeatureArch}}
            if ($FeatureBuild) {$FeatureUpdateDownloads = $FeatureUpdateDownloads | Where-Object {$_.UpdateBuild -eq $FeatureBuild}}
            if ($FeatureEdition) {$FeatureUpdateDownloads = $FeatureUpdateDownloads | Where-Object {$_.Title -match $FeatureEdition}}
            if ($FeatureLang) {
                $regex = $FeatureLang.ForEach({ [RegEx]::Escape($_) }) -join '|'
                $FeatureUpdateDownloads = $FeatureUpdateDownloads | Where-Object {$_.Title -match $regex}
            }
            #===================================================================================================
            # Select-Object
            #===================================================================================================
            $FeatureUpdateDownloads = $FeatureUpdateDownloads | Select-Object -Property OSDStatus, Title, UpdateOS,`
            UpdateBuild, UpdateArch, CreationDate, KBNumber, FileName, Size, OriginUri, Hash, AdditionalHash
            #===================================================================================================
            # Sorting
            #===================================================================================================
            $FeatureUpdateDownloads = $FeatureUpdateDownloads | Sort-Object -Property Title
            #===================================================================================================
            # Select Updates with GridView
            #===================================================================================================
            if (! ($SkipGridView.IsPresent)) {
                $FeatureUpdateDownloads = $FeatureUpdateDownloads | Out-GridView -PassThru -Title 'Select ESD Files to Download and Build and press OK'
            }
            #===================================================================================================
            # Download Updates
            #===================================================================================================
            if ($WebClient.IsPresent) {$WebClientObj = New-Object System.Net.WebClient}
            foreach ($Item in $FeatureUpdateDownloads) {
                $DownloadFullPath = Join-Path $SetOSDBuilderPathFeatureUpdates $Item.FileName

                if (!(Test-Path $SetOSDBuilderPathFeatureUpdates)) {New-Item -Path $SetOSDBuilderPathFeatureUpdates -ItemType Directory -Force | Out-Null}
                Write-Host "$DownloadFullPath" -ForegroundColor Cyan
                Write-Host "$($Item.OriginUri)" -ForegroundColor DarkGray
                if (!(Test-Path $DownloadFullPath)) {
                    if ($WebClient.IsPresent) {                            
                        $WebClientObj.DownloadFile("$($Item.OriginUri)","$DownloadFullPath")
                    } else {
                        Start-BitsTransfer -Source $Item.OriginUri -Destination $DownloadFullPath -ErrorAction Stop
                    }
                }

                if (!(Test-Path $DownloadFullPath)) {
                    Write-Warning "Could not complete download of $DownloadFullPath"
                    Break
                }

                $esdbasename = (Get-Item "$DownloadFullPath").Basename
                $esddirectory = Join-Path $SetOSDBuilderPathFeatureUpdates $esdbasename

                if (Test-Path "$esddirectory\Sources\Install.wim") {
                    Write-Verbose "Image already exists at $esddirectory\Sources\Install.wim" -Verbose
                } else {
                    Try {$esdinfo = Get-WindowsImage -ImagePath "$DownloadFullPath"}
                    Catch {
                        Write-Warning "Could not get ESD information"
                        Break
                    }
                    Write-Host "Creating $esddirectory" -ForegroundColor Cyan
                    New-Item -Path "$esddirectory" -Force -ItemType Directory | Out-Null
                    
                    foreach ($image in $esdinfo) {
                        if ($image.ImageName -eq 'Windows Setup Media') {
                            Write-Host "Expanding Index $($image.ImageIndex) $($image.ImageName) ..." -ForegroundColor Cyan
                            Expand-WindowsImage -ImagePath "$($image.ImagePath)" -ApplyPath "$esddirectory" -Index "$($image.ImageIndex)" -ErrorAction SilentlyContinue | Out-Null
                        } elseif ($image.ImageName -like "*Windows PE*") {
                            Write-Host "Exporting Index $($image.ImageIndex) $($image.ImageName) ..." -ForegroundColor Cyan
                            Export-WindowsImage -SourceImagePath "$($image.ImagePath)" -SourceIndex $($image.ImageIndex) -DestinationImagePath "$esddirectory\sources\boot.wim" -CompressionType Max -ErrorAction SilentlyContinue | Out-Null
                        } elseif ($image.ImageName -like "*Windows Setup*") {
                            Write-Host "Exporting Index $($image.ImageIndex) $($image.ImageName) ..." -ForegroundColor Cyan
                            Export-WindowsImage -SourceImagePath "$($image.ImagePath)" -SourceIndex $($image.ImageIndex) -DestinationImagePath "$esddirectory\sources\boot.wim" -CompressionType Max -Setbootable -ErrorAction SilentlyContinue | Out-Null
                        } else {
                            Write-Host "Exporting Index $($image.ImageIndex) $($image.ImageName) ..." -ForegroundColor Cyan
                            Export-WindowsImage -SourceImagePath "$($image.ImagePath)" -SourceIndex $($image.ImageIndex) -DestinationImagePath "$esddirectory\sources\install.wim" -CompressionType Max -ErrorAction SilentlyContinue | Out-Null
                        }
                    }
                }
            }
            Write-Warning "Use Import-OSMedia to import this Feature Update to OSMedia"
        }


        if ($PSCmdlet.ParameterSetName -eq 'Content') {
            #===================================================================================================
            # Database
            #===================================================================================================
            if ($ContentDownload -eq 'OneDriveSetup Production') {
                $DownloadUrl = 'https://go.microsoft.com/fwlink/p/?LinkId=248256'
                $DownloadPath = $GetOSDBuilderPathContentOneDrive
                $DownloadFile = 'OneDriveSetup.exe'
            }
            if ($ContentDownload -eq 'OneDriveSetup Enterprise') {
                $DownloadUrl = 'https://go.microsoft.com/fwlink/p/?linkid=860987'
                $DownloadPath = $GetOSDBuilderPathContentOneDrive
                $DownloadFile = 'OneDriveSetup.exe'
            }
            #===================================================================================================
            # Download
            #===================================================================================================
            if (!(Test-Path "$DownloadPath")) {New-Item -Path $DownloadPath -ItemType Directory -Force | Out-Null}
            Write-Verbose "DownloadUrl: $DownloadUrl" -Verbose
            Write-Verbose "DownloadPath: $DownloadPath" -Verbose
            Write-Verbose "DownloadFile: $DownloadFile" -Verbose
            Invoke-WebRequest -Uri $DownloadUrl -OutFile "$DownloadPath\$DownloadFile"
            if (Test-Path "$DownloadPath\$DownloadFile") {
                $OneDriveSetupInfo = Get-Item -Path "$DownloadPath\$DownloadFile" | Select-Object -Property *
                Write-Verbose "DownloadVersion: $($($OneDriveSetupInfo).VersionInfo.ProductVersion)" -Verbose
                Write-Verbose 'Complete' -Verbose
            } else {
                Write-Warning 'Content could not be downloaded'
            }
        }

        
        if (($PSCmdlet.ParameterSetName -eq 'OSDUpdate') -or ($PSCmdlet.ParameterSetName -eq 'OSDUpdateSuperseded')) {
            #===================================================================================================
            # Information
            #===================================================================================================
            if ($WebClient.IsPresent) {
                Write-Verbose "Downloading OSDUpdates using System.Net.WebClient" -Verbose
            } else {
                Write-Verbose "Downloading OSDUpdates using BITS-Transfer" -Verbose
                Write-Verbose "To use System.Net.WebClient, use the -WebClient Parameter" -Verbose
            }
            #===================================================================================================
            # Get OSDUpdates
            #===================================================================================================
            $OSDUpdates = @()
            $OSDUpdates = Get-OSDUpdates | Sort-Object CreationDate -Descending
            #===================================================================================================
            # Superseded Updates
            #===================================================================================================
            if ($Superseded) {
                $ExistingUpdates = @()
                if (!(Test-Path $SetOSDBuilderPathUpdates)) {New-Item $SetOSDBuilderPathUpdates -ItemType Directory -Force | Out-Null}
                $ExistingUpdates = Get-ChildItem -Path "$SetOSDBuilderPathUpdates\*\*" -Directory

                $SupersededUpdates = @()
                foreach ($Update in $ExistingUpdates) {
                    if ($OSDUpdates.Title -NotContains $Update.Name) {$SupersededUpdates += $Update.FullName}
                }
            
                if ($Superseded -eq 'List') {
                    Write-Warning 'Superseded Updates:'
                    foreach ($Update in $SupersededUpdates) {
                        Write-Host "$Update" -ForegroundColor Gray
                    }
                }
                if ($Superseded -eq 'Remove') {
                    Write-Warning 'Superseded Updates:'
                    foreach ($Update in $SupersededUpdates) {
                        Write-Warning "Deleting $Update"
                        Remove-Item $Update -Recurse -Force | Out-Null
                    }
                }
                Break
            }
            #===================================================================================================
            # Filters
            #===================================================================================================
            if ($UpdateOS) {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateOS -eq $UpdateOS}}
            if ($UpdateArch) {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateArch -eq $UpdateArch}}
            if ($UpdateBuild) {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateBuild -eq $UpdateBuild}}
            #===================================================================================================
            # UpdateGroup
            #===================================================================================================
            if ($UpdateGroup -like "*Adobe*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -eq 'AdobeSU'}}
            if ($UpdateGroup -like "*DotNet*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -like "DotNet*"}}
            if ($UpdateGroup -like "*DUCU*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -like "ComponentDU*"}}
            if ($UpdateGroup -like "*DUSU*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -eq 'SetupDU'}}
            if ($UpdateGroup -like "*LCU*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -eq 'LCU'}}
            if ($UpdateGroup -like "*SSU*") {$OSDUpdates = $OSDUpdates | Where-Object {$_.UpdateGroup -eq 'SSU'}}
            if ($UpdateGroup -eq 'Optional') {$OSDUpdates = $OSDUpdates | Where-Object {[String]::IsNullOrWhiteSpace($_.UpdateGroup) -or $_.UpdateGroup -eq 'Optional'}}
            #===================================================================================================
            # Sorting
            #===================================================================================================
            $OSDUpdates = $OSDUpdates | Sort-Object -Property CreationDate -Descending
            #===================================================================================================
            # Select Updates with GridView
            #===================================================================================================
            if ($GridView.IsPresent) {$OSDUpdates = $OSDUpdates | Out-GridView -PassThru -Title 'Select Updates to Download and press OK'}
            #===================================================================================================
            # Download Updates
            #===================================================================================================
            if ($Download.IsPresent) {
                if ($WebClient.IsPresent) {$WebClientObj = New-Object System.Net.WebClient}
                foreach ($Update in $OSDUpdates) {
                    $DownloadPath = "$SetOSDBuilderPathUpdates\$($Update.Catalog)\$($Update.Title)"
                    $DownloadFullPath = "$DownloadPath\$($Update.FileName)"

                    if (!(Test-Path $DownloadPath)) {New-Item -Path "$DownloadPath" -ItemType Directory -Force | Out-Null}
                    if (!(Test-Path $DownloadFullPath)) {
                        Write-Host "$DownloadFullPath" -ForegroundColor Cyan
                        Write-Host "$($Update.OriginUri)" -ForegroundColor DarkGray
                        if ($WebClient.IsPresent) {                            
                            $WebClientObj.DownloadFile("$($Update.OriginUri)","$DownloadFullPath")
                        } else {
                            Start-BitsTransfer -Source $Update.OriginUri -Destination $DownloadFullPath
                        }
                        if ($CheckFileHash.IsPresent -and ($Update.Hash -ne "")) {
                            $ActualHash = $null
                            $ActualHash = (Get-FileHash -Path $DownloadFullPath -Algorithm SHA1).Hash.ToLower()
                            $DeriredHash = Convert-ByteArrayToHex -Bytes $($update.Hash -split " ")
                            Write-Verbose "Desired SHA1 Hash: [$DeriredHash], Actual Hash [$ActualHash]"
                            if ($ActualHash -ne $DeriredHash) {
                                Write-Error -Exception "Hashes don't match - please investigate!" 
                            }
                            else {
                                Write-Verbose -Message "Hashes match."
                            }
                        }
                    } else {
                        #Write-Warning "Exists: $($Update.Title)"
                    }
                }
            } else {
                Return $OSDUpdates | Select-Object -Property Catalog, OSDVersion, OSDStatus, UpdateOS, UpdateBuild, UpdateArch, UpdateGroup, CreationDate, KBNumber, Title
            }
        }
    }

    END {
        #Write-Host '========================================================================================' -ForegroundColor DarkGray
        #Write-Host -ForegroundColor Green "$($MyInvocation.MyCommand.Name) END"
    }
}