I'm trying to write a PowerShell script that does the following:
Is it possible to get the file size of an online file without downloading it? I tried using .length but it didn't work. (I'm new to PowerShell)
PS Script:
$localpath = "C:\Users\USERNAME\Desktop\test.csv"
If(Test-Path -Path $localpath)
{
#Exist, check for an updated version
$localFileSize = (Get-Item $localpath).length
$onlineFileSize = (Get-Item 'test.com/test.txt').length
if($onlineFileSize -gt $localFileSize)
{
$url = "test.com/test.txt"
$downloadFile = "C:\Users\USERNAME\Desktop\test.csv"
(New-Object System.Net.WebClient).DownloadFile($url, $downloadFile)
}
} else
{
#Does not exist, download the file
$url = "test.com/test.txt"
$downloadFile = "C:\Users\USERNAME\Desktop\test.csv"
(New-Object System.Net.WebClient).DownloadFile($url, $downloadFile)
}
You can use Invoke-WebRequest
and use the HEAD
method to get just the headers and not download anything. If the resource you're requesting has a known length, then you'll get a Content-Length
header which you can use, e.g.
(Invoke-WebRequest $url -Method Head).Headers.'Content-Length'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With