簡體   English   中英

如何僅在使用 powershell 更改文件時才下載文件

[英]How can I download a file only if it has changed using powershell

我正在使用這個簡單的函數來下載文件:

function DownloadFile([string]$url, [string]$file)
{
    $clnt = new-object System.Net.WebClient
    Write-Host "Downloading from $url to $file " 
    $clnt.DownloadFile($url, $file)
}

它工作正常,但我正在使用的腳本調用它可以多次調用,目前這可能意味着多次下載文件。

如果文件在本地不存在或服務器版本較新(例如,服務器上的 LastModifiedDate 大於本地的 LastModifiedDate),我該如何修改該函數以僅下載?

編輯:這是我到目前為止所得到的,似乎可以工作,但不希望對服務器進行 2 次調用。

function DownloadFile([string]$url, [string]$file)
{
    $downloadRequired = $true
    if ((test-path $file)) 
    {
        $localModified = (Get-Item $file).LastWriteTime 
        $webRequest = [System.Net.HttpWebRequest]::Create($url);
        $webRequest.Method = "HEAD";
        $webResponse = $webRequest.GetResponse()
        $remoteLastModified = ($webResponse.LastModified) -as [DateTime] 
        $webResponse.Close()

        if ($remoteLastModified -gt $localModified)
        {
            Write-Host "$file is out of date"
        }
        else
        {
            $downloadRequired = $false
        }

    }

    if ($downloadRequired)
    {
        $clnt = new-object System.Net.WebClient
        Write-Host "Downloading from $url to $file"
        $clnt.DownloadFile($url, $file)
    }
    else
    {
        Write-Host "$file is up to date."
    }
}

這周我一直在解決這個問題,並想出了這個

 # ---------------------------------------------------------------------------------------------- # download a file # ---------------------------------------------------------------------------------------------- Function Download-File { Param ( [Parameter(Mandatory=$True)] [System.Uri]$uri, [Parameter(Mandatory=$True )] [string]$FilePath ) #Make sure the destination directory exists #System.IO.FileInfo works even if the file/dir doesn't exist, which is better then get-item which requires the file to exist If (! ( Test-Path ([System.IO.FileInfo]$FilePath).DirectoryName ) ) { [void](New-Item ([System.IO.FileInfo]$FilePath).DirectoryName -force -type directory)} #see if this file exists if ( -not (Test-Path $FilePath) ) { #use simple download [void] (New-Object System.Net.WebClient).DownloadFile($uri.ToString(), $FilePath) } else { try { #use HttpWebRequest to download file $webRequest = [System.Net.HttpWebRequest]::Create($uri); $webRequest.IfModifiedSince = ([System.IO.FileInfo]$FilePath).LastWriteTime $webRequest.Method = "GET"; [System.Net.HttpWebResponse]$webResponse = $webRequest.GetResponse() #Read HTTP result from the $webResponse $stream = New-Object System.IO.StreamReader($webResponse.GetResponseStream()) #Save to file $stream.ReadToEnd() | Set-Content -Path $FilePath -Force } catch [System.Net.WebException] { #Check for a 304 if ($_.Exception.Response.StatusCode -eq [System.Net.HttpStatusCode]::NotModified) { Write-Host " $FilePath not modified, not downloading..." } else { #Unexpected error $Status = $_.Exception.Response.StatusCode $msg = $_.Exception Write-Host " Error dowloading $FilePath, Status code: $Status - $msg" } } } }

最后修改在 HTTP 響應標頭中。

嘗試這個:

$clnt.OpenRead($Url).Close();
$UrlLastModified = $clnt.ResponseHeaders["Last-Modified"];

如果該日期比您文件上的日期新,則您的文件已舊。

遠程服務器不必以准確的日期或文件的實際上次修改日期進行響應,但許多會響應。

GetWebResponse()可能是執行此操作的更好方法(或更正確的方法)。 之后立即使用OpenRead()Close()困擾着我的感受,但我可能瘋了。 我主要從事數據庫方面的工作。

# If the local directory exists and it gets a response from the url,
# it checks the last modified date of the remote file. If the file
# already exists it compares the date of the file to the file from
# the url. If either the file doesn't exists or has a newer date, it
# downloads the file and modifies the file's date to match.

function download( $url, $dir, $file ) {
 if( Test-Path $dir -Ea 0 ) {
  $web = try { [System.Net.WebRequest]::Create("$url/$file").GetResponse() } catch [Net.WebException] {}
  if( $web.LastModified ) {
   $download = 0
   if(-Not(Test-Path "$dir\$file" -Ea 0)) { $download = 1 }
   elseif((gi "$dir\$file").LastWriteTime -ne $web.LastModified) { $download = 1 }
   if( $download ) {
    Invoke-WebRequest "$url/$file" -OutFile "$dir\$file" | Wait-Process
    (gi "$dir\$file").LastWriteTime = $web.LastModified
   }
   $web.Close()
  }
 }
}
download "https://website.com" "$env:systemdrive" "file.txt"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM