我试图使用PowerShell下载目标文件名未知的文件?

时间:2018-06-15 16:28:36

标签: powershell google-drive-realtime-api webclient-download

我使用以下脚本使用PowerShell下载文件。

 $folder = "c:\temp\"
$userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 
Firefox/7.0.1"
$web = New-Object System.Net.WebClient
$web.Headers.Add("user-agent", $userAgent)


Get-Content "c:\temp\URL_List.txt" |
Foreach-Object { 
"Downloading " + $_
try {
    $target = join-path $folder ([io.path]::getfilename($_))
    $web.DownloadFile($_, $target)
} catch {
    $_.Exception.Message
}

}

URL_List.txt文件包含我尝试从中下载文件的网址列表。以下是列表中的示例网址:https://drive.google.com/uc?export=download&id=0B84LPHCa2YmdZmFMV0dsYl9FeTg 如果您查看URL,URL中没有绝对文件名,因此我不确定如何为WebClient.DownloadFile()方法设置目标参数。

2 个答案:

答案 0 :(得分:0)

阅读Download Files。也可能值得检查,因为您正在使用Powershell,Google Drive REST Api module for Powershell

答案 1 :(得分:0)

因此,据我了解,问题是如何在不先下载文件的情况下提取Google云端硬盘文件的文件名

这个Chilkat page给我的想法是,应该可以通过GET请求访问属性。 Chilkat是一种付费API,所以我想我会尝试使用直接PowerShell命令拼凑一种方法。

Invoke-WebRequest有效,但会下载整个文件。我们只需要标题。

This site拥有核心代码。从那里,它只是解析Content-Disposition标头以提取“文件名”(和 not “ filename *”):

$WebPath = "https://drive.google.com/uc?export=download&id=0B84LPHCa2YmdZmFMV0dsYl9FeTg"
$request = [System.Net.WebRequest]::Create( $WebPath ) 
$headers = $request.GetResponse().Headers 
# Content-disposition includes a name-value pair for filename:
$cd = $headers.GetValues("Content-Disposition")
$cd_array = $cd.split(";")
foreach ($item in $cd_array) { 
  if ($item.StartsWith("filename=")) {
      # Get string after equal sign
      $filename = $item.Substring($item.IndexOf("=")+1)
      # Remove quotation marks, if any
      $filename = $filename.Replace('"','')
  }
}