How to name downloaded file?

60 views Asked by At

My boss has asked me to create a function/Script to download files off a website and place them in a folder:

Add-Type -AssemblyName Microsoft.Visualbasic

$url = "http://www.rarlab.com/rar/wrar521.exe"
$output = "C:\Users\****\Downloads\test\1"

$object = New-Object Net.WebClient
$object.DownloadFile($url, $output)


#######################################
$start_time = Get-Date
Write-Output "Time Taken((Get-Date).Subtract($start_time).Seconds) second(s)"

This is the current code I've got. Basically, what I need it to do is automatically name the file or resolve the name from the server with out me having to put $output = "C:\Users\****\Downloads\test\test.txt" or something.

1

There are 1 answers

0
Ansgar Wiechers On

Use Split-Path to split the filename from the URL, and Join-Path to join it to the folder path:

$url      = 'http://www.rarlab.com/rar/wrar521.exe'
$filename = Split-Path -Leaf $url
$output   = Join-Path 'C:\Users\****\Downloads\test\1' $filename

(New-Object Net.WebClient).DownloadFile($url, $output)