Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the file size of a file located online via PowerShell?

Tags:

powershell

I'm trying to write a PowerShell script that does the following:

  • Check whether a specific file exist on the PC
  • If it exists, compare the local file size to the online file size. If the online file size is greater than the local file size, download the file. (Checks for an updated version)
  • If it does not exist, download the file from the website.

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)
}
like image 410
mdinh1 Avatar asked Aug 31 '25 22:08

mdinh1


1 Answers

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'
like image 80
Joey Avatar answered Sep 04 '25 03:09

Joey