首页 > 解决方案 > 我正在尝试使用 PowerShell 下载目标文件名未知的文件?

问题描述

我正在使用以下脚本使用 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 文件包含我要从中下载文件的 URL 列表。这是列表中的示例 URL:https ://drive.google.com/uc?export=download&id=0B84LPHCa2YmdZmFMV0dsYl9FeTg 如果您查看 URL,则 URL 中没有绝对文件名,所以我不确定如何设置目标WebClient.DownloadFile() 方法的参数。

标签: powershellgoogle-drive-realtime-apiwebclient

解决方案


因此,据我所知,问题是如何在不先下载文件的情况下提取 Google Drive 文件的文件名

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

Invoke-WebRequest工作,但下载整个文件。我们只需要标题。

这个网站有核心代码。从那里,它只是解析 Content-Disposition 标头以提取“文件名”(而不是“文件名*”):

$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('"','')
  }
}

推荐阅读