Search This Blog

Wednesday 17 October 2018

Powershell download new version of script

I have a number of scripts that I occasionally need to run on servers.  The source for these scripts lives in VSTS, so I add the following code so that I can simply use an " -update " switch to fetch the latest code from VSTS and overwrite the local copy.

 [CmdletBinding()]
param (
    [Switch] $Update
)

# use -Update switch to download latest version of this script


$VSTSUsername = "d.duck@disney.com"
$VSTSPassword = "password"


########################################################################################################

function DownloadFile {

    param ($uri, $targetFilename)

    write-host "Downloading '$targetFilename' from '$uri'"

    #clean working folder
    Remove-Item $targetFilename -Force -ErrorAction SilentlyContinue

    #download file
    $pair = "$($VSTSUsername):$($VSTSPassword)"
    $encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
    $basicAuthValue = "Basic $encodedCreds"
    $Headers = @{Authorization = $basicAuthValue}
    Invoke-WebRequest -Uri $uri -OutFile $targetFilename -Headers $Headers

}

########################################################################################################


if ($update) {
    DownloadFile -targetFilename "webserver.ps1" -uri "https://disney.visualstudio.com/45cd2ctt-367a-49a8-8eeb-2bmm3653b4d8/_apis/git/repositories/46067735-14ce-43ha-9368-122a6e2611dd/Items?path=%2FSafn%2FWebServers%2Fwebserver.ps1&versionDescriptor%5BversionOptions%5D=0&versionDescriptor%5BversionType%5D=0&versionDescriptor%5Bversion%5D=master&download=true&resolveLfs=true&%24format=octetStream&api-version=5.0-preview.1"
    Write-Host "Latest version of 'webserver.ps1' has been downloaded" -ForegroundColor Cyan
    exit
}


# if -script is absent, code below this point will run





To find the URL of you file, you can use the following steps:

In your VSTS repo, download the file you want:



After it has downloaded, open the Chrome downloads dialog:


Find the download in the list and you can see the URL:



No comments:

Post a Comment