我有一個包含多個網址的文件這樣的文件下載的文件的文件名:閱讀使用PowerShell
http://ligman.me/1HCDxl9
http://ligman.me/1HCCCRP
http://ligman.me/1HCCCRP
http://ligman.me/1H4Q0e5
http://ligman.me/1H4Q0e5
http://ligman.me/1JI6V77
http://ligman.me/1JI6V77
http://ligman.me/1CSMobd
http://ligman.me/1CSMobd
我想寫一個PowerShell腳本將逐行讀取該文件中的行,然後下載每行後面的文件(URL)。到目前爲止,我已經設法使用以下腳本下載文件:
$reader = [System.IO.File]::ReadLines("C:\Temp\Ebooks\ebooks.txt") | Where-Object { $_ -ne '' }
$targetDir = "C:\Temp\Ebooks\"
$wc = New-Object System.Net.WebClient
foreach($file in $reader) {
$sourceFileName = $file.SubString($file.LastIndexOf('/')+1) + ".pdf"
$targetFileName = $targetDir + $sourceFileName
$wc.DownloadFile($file, $targetFileName)
Write-Host "Downloaded $file successfully to directory $targetDir"
}
我的問題是文件名。現在,我只能將它們保存爲PDF格式,但有時文件不是PDF文件,而是DOCX或XLSX。另外,如果它們不被命名爲1225DID或13DChwr,那將會很好。基本上,我仍然需要讀取實際的文件名,然後用該名稱保存下載的文件。
我該怎麼做?
編輯:這是工作得到實際的文件名,但當我嘗試打開文件時,我得到一個錯誤,他們不是PDF或已損壞(只要我嘗試用福昕閱讀器打開PDF文件)
$reader = [System.IO.File]::ReadLines("C:\Temp\Ebooks\ebooks.txt") | Where-Object { $_ -ne '' }
$targetDir = "C:\Temp\Ebooks\"
$wc = New-Object System.Net.WebClient
$reader | %{
$uri = $_
$request = Invoke-WebRequest -Uri $uri -MaximumRedirection 0 -ErrorAction Ignore
$sourceFileName = $request.Headers.Location.SubString($request.Headers.Location.LastIndexOf('/') + 1)
$targetFileName = $targetDir + $sourceFileName
$wc.DownloadFile($file, $targetFileName)
Write-Host "Downloaded $file successfully to directory $targetDir"
}
您能分享您試圖目標實際的URL之一,之類的東西的例子具有相同的格式? – Bassie
確定我編輯爲網址,它們應該現在有效 – LeonidasFett
我已經嘗試閱讀這些文件的內容處置,但它似乎只有「附件」作爲值,沒有別的。 – LeonidasFett