如何通过 PowerShell 获取在线文件的文件大小? [英] How do I get the file size of a file located online via PowerShell?

查看:166
本文介绍了如何通过 PowerShell 获取在线文件的文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个执行以下操作的 PowerShell 脚本:

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

  • 检查PC上是否存在特定文件
  • 如果存在,将本地文件大小与在线文件大小进行比较.如果在线文件大小大于本地文件大小,则下载文件.(检查更新版本)
  • 如果文件不存在,请从网站下载该文件.

是否可以在不下载的情况下获取在线文件的文件大小?我尝试使用 .length 但它没有用.(我是 PowerShell 的新手)

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 脚本:

$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)
}

推荐答案

您可以使用 Invoke-WebRequest 并使用 HEAD 方法只获取标题而不下载任何事物.如果您请求的资源具有已知长度,那么您将获得一个可以使用的 Content-Length 标头,例如

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'

这篇关于如何通过 PowerShell 获取在线文件的文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆