powershell - 我正在尝试使用 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() 方法的参数。
解决方案
因此,据我所知,问题是如何在不先下载文件的情况下提取 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('"','')
}
}
推荐阅读
- python - 如何使用普通文本加入列
- jinja2 - 如何隐式地拥有全局自定义宏使用上下文?
- javascript - 对机器人发布的消息做出反应
- go - LeetCode 问题 Path Sum II: Recursive solution bug
- node.js - Node + Express Backend:调用第三方API
- c++ - 为 HP-35 C++ 程序实现科学函数
- python-3.x - 顶层窗口小部件在父窗口上创建
- javascript - 为什么 highcharts 不接受第二个 y 轴的数组?
- node.js - 快速重定向但不显示任何数据?
- docker - 任何人都可以帮助修复 curl:(7)无法连接到端口 80:连接被拒绝