Why Are Some PDF Files Downloading with PowerShell While Others Fail?
Asked by
CuriousCoder42
Hey everyone,
I'm working on a PowerShell script to download PDF files from a specific site using the following code on my first attempt:
```powershell
$credential = Get-Credential
$edgePath = "C:Program Files (x86)MicrosoftEdgeApplicationmsedge.exe"
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$startcounter = 2
while ($startcounter -lt 100){
$url = "https:[site]/$startcounter.pdf"
$dest = "C:Temp$startcounter.PDF"
write $url
$web = Invoke-WebRequest -uri $url -SessionVariable session -Credential $credential -OutFile $dest
$startcounter++
start-sleep -Seconds 1
}
```
I'm running into a problem where I'm getting an error message for many of the downloads: "Invoke-WebRequest : {"status":"ERROR","errors":["Not Found"],"results":[]} "
Out of 100 files, I could only successfully download 25. However, I can still access the files that produce an error when I use Edge. Any ideas on why some files download while others don't? Thanks!
Answers
It sounds like your browser keeps track of cookies, headers, and session info that your script isnโt using. When you call Invoke-WebRequest, it starts a new session each time, which means it might miss any necessary authentication or additional data. That's likely why you're seeing the "Not Found" error for some files.
Reply to this answer
Add your answer
Answers are reviewed before publication.
CleverCat23: Thanks for the insight! But I'm puzzledโif I try downloading a specific file that returns an error, #2 for instance, I can get it through Edge without a hitch. Any thoughts on that? Why does it work in the browser but not in the script?