Public/Save-OSDDownload.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
<#
.SYNOPSIS
Downloads a file from the internet
 
.DESCRIPTION
Downloads a file from the internet. Success returns $true
 
.LINK
https://osd.osdeploy.com/module/functions/save-osddownload
 
.NOTES
19.10.25 David Segura @SeguraOSD
#>

function Save-OSDDownload {
    [CmdletBinding()]
    Param (
        #URL of the file to download
        [Parameter(Mandatory)]
        [string]$SourceUrl,

        #Destination Folder
        [string]$DownloadFolder = $env:TEMP,

        #Overwrite the file if it exists already
        #The default action is to skip the download
        [switch]$Overwrite,

        #Download the file using BITS-Transfer
        #Interactive Login required
        [switch]$BitsTransfer
    )
    
    $global:OSDDownload = [ordered]@{
        Name = $null
        FullName = $null
        DownloadFolder = $DownloadFolder
        SourceUrl = $SourceUrl
        BitsTransfer = $BitsTransfer
        Download = $true
        IsDownloaded = $false
    }


    $global:OSDDownload.Name = Split-Path -Path $OSDDownload.SourceUrl -Leaf
    Write-Verbose "OSDDownload Name: $($OSDDownload.Name)"

    $global:OSDDownload.FullName = Join-Path $DownloadFolder $OSDDownload.Name
    Write-Verbose "OSDDownload FullName: $($OSDDownload.FullName)"

    #======================================================================================================
    #    DownloadFolder
    # Make sure DownloadFolder can be created
    #======================================================================================================
    if (! (Test-Path "$DownloadFolder")) {
        Write-Verbose "New-Item -Path $DownloadFolder"
        New-Item -Path "$DownloadFolder" -ItemType Directory -Force | Out-Null
        if (!(Test-Path $DownloadFolder)) {
            Return $global:OSDDownload
        }
    }

    if (!($Overwrite.IsPresent)) {
        if (Test-Path $OSDDownload.FullName) {
            $global:OSDDownload.IsDownloaded = $true
            Return $global:OSDDownload
        }
    }

    if ($BitsTransfer.IsPresent) {Start-BitsTransfer -Source $SourceUrl -Destination $OSDDownload.FullName}
    else {
        $WebClient = New-Object System.Net.WebClient
        $WebClient.OSDDownload.Name($SourceUrl,$OSDDownload.FullName)
    }

    if (Test-Path $OSDDownload.FullName) {
        $global:OSDDownload.IsDownloaded = $true
    }
    Return $global:OSDDownload
}