【问题标题】:I am trying to download files using PowerShell where target file name is not known?我正在尝试使用 PowerShell 下载目标文件名未知的文件?
【发布时间】:2018-06-15 16:28:35
【问题描述】:

我正在使用以下脚本通过 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() 方法设置目标参数。

【问题讨论】:

  • 您有什么方法可以在下载文件后导出文件名吗?您可以使用[System.IO.Path]::GetTempFileName() 生成一个 tmp 文件以将请求写入其中,直到您弄清楚它的名称。另外,什么版本的 PowerShell?您应该使用 Invoke-WebRequest -OutFile 而不是手动操作 .net(作为最佳实践)

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    所以我理解的问题是如何在不先下载文件的情况下提取 Google Drive 文件的文件名

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多