Functions/Install-ToolFromUrl.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
function Install-ToolFromUrl {
    [CmdletBinding()]
    param ([string] $ToolPath
        , [string] $url
        )
    
    New-ToolPath $ToolPath
        
    [System.Net.HttpWebResponse] $zipHttpResponse = [System.Net.WebRequest]::Create($url).GetResponse();

    #Meta data file to store information about the download for future comparisons
    $MetaDataFilePath = Get-MetadataFile  $ToolPath

    if (Test-ShouldDownload -MetaDataFilePath $MetaDataFilePath -zipHttpResponse $zipHttpResponse) {
        $toolzip = join-path $ToolPath "$toolName.zip"
        Invoke-WebRequest  $url -OutFile $toolzip
        Expand-Archive -Path  $toolzip -DestinationPath $ToolPath -Force 
        Save-MetaDataToFile $MetaDataFilePath $zipHttpResponse
    }
    $zipHttpResponse.Close()
    $zipHttpResponse.Dispose()
    
    Write-Host "$toolName installed"
}
function Set-EnvironmentVariablesFromTool {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param ($EnvironmentSettings)
    $EnvironmentSettings | ForEach-Object { 
        Set-item env:"$_.environmentvariable"  (join-path $ToolPath $_.path) }
}

function New-ToolPath {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param($ToolPath)

    if (-not ( Test-path $ToolPath)) {
        if ($PSCmdlet.ShouldProcess("ShouldProcess?")) {
            New-Item -ItemType Directory -Path $ToolPath | Out-Null
        }
    }
}

function Test-ShouldDownload {
    param($MetaDataFilePath
        , $zipHttpResponse)

    $downloadZip = $false
    if (Test-path $MetaDataFilePath) {
        $SqlpackageMetaData = Get-Content  $MetaDataFilePath -Raw | Convertfrom-json
        #Check the metadata from the URL compared with the previous download
        if ($SqlpackageMetaData.Size -ne $zipHttpResponse.ContentLength -or `
                $SqlpackageMetaData.Filename -ne $zipHttpResponse.ResponseUri.Segments[-1] ) {
            $downloadZip = $true
        }
    }
    else {
        $downloadZip = $true
    }

    return $downloadZip
} 
function Get-MetaDataFile {
    param ($ToolFolder)
    return join-path $ToolFolder "metadata.json"
}
function Save-MetaDataToFile {
    param($MetaDataFilePath
        , $zipHttpResponse)
    @{Size       = $zipHttpResponse.ContentLength; 
        Filename = $zipHttpResponse.ResponseUri.Segments[-1] 
    } `
    | convertto-json | out-file $MetaDataFilePath
}