Skip to content

Instantly share code, notes, and snippets.

@SidShetye
Last active March 27, 2024 15:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SidShetye/3d0570d8514f4388346d8af9f314920c to your computer and use it in GitHub Desktop.
Save SidShetye/3d0570d8514f4388346d8af9f314920c to your computer and use it in GitHub Desktop.
Powershell script to download files on Windows Server Nano where Invoke-Webrequest/wget are natively missing
<#
.SYNOPSIS
Downloads a file
.DESCRIPTION
Downloads a file
.PARAMETER Url
URL to file/resource to download
.PARAMETER Filename
file to save it as locally
.EXAMPLE
C:\PS> .\wget.ps1 https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
#>
Param(
[Parameter(Position=0,mandatory=$true)]
[string]$Url,
[string]$Filename = ''
)
# Get filename
if (!$Filename) {
$Filename = [System.IO.Path]::GetFileName($Url)
}
Write-Host "Download: $Url to $Filename"
# Make absolute local path
if (![System.IO.Path]::IsPathRooted($Filename)) {
$FilePath = Join-Path (Get-Item -Path ".\" -Verbose).FullName $Filename
}
if (($Url -as [System.URI]).AbsoluteURI -ne $null)
{
# Download the bits
$handler = New-Object System.Net.Http.HttpClientHandler
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = New-Object System.TimeSpan(0, 30, 0)
$cancelTokenSource = [System.Threading.CancellationTokenSource]::new()
$responseMsg = $client.GetAsync([System.Uri]::new($Url), $cancelTokenSource.Token)
$responseMsg.Wait()
if (!$responseMsg.IsCanceled)
{
$response = $responseMsg.Result
if ($response.IsSuccessStatusCode)
{
$downloadedFileStream = [System.IO.FileStream]::new($FilePath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$copyStreamOp = $response.Content.CopyToAsync($downloadedFileStream)
# TODO: Progress bar? Total size?
Write-Host "Downloading ..."
$copyStreamOp.Wait()
$downloadedFileStream.Close()
if ($copyStreamOp.Exception -ne $null)
{
throw $copyStreamOp.Exception
}
}
}
}
else
{
throw "Cannot download from $Url"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment