Powershell download file from website ie.document

2019-07-16 07:19发布

问题:

I have created a little script that log's on to a https website using Internet explore 11. I had a manual mouse click to Download file to IE but im getting the prompt to save open file I would like to be able to bypass this due to im going to run this in the back ground? Am I missing a param on the end of my ie.navigate(url) to just save the file? As I stated above I'm using IE11 for this and downgrading is not an option.

Any help would be great

$username= get-content -Path c:\username.txt
$password= get-content -Path c:\password.txt

$ie = New-Object -ComObject internetExplorer.Application
$ie.Visible= $false
$ie.fullscreen = $false

$ie.Navigate("https://www.mft1.firstdataclients.com/cgi-bin/messageway/mwi.cgi")

while ($ie.Busy -eq $true){Start-Sleep -seconds 2}  

$usernamefield = $ie.Document.getElementByID('user')
$usernamefield.value = $username

$passwordfield = $ie.Document.getElementByID('password')
$passwordfield.value = $password

$ie.document.getElementById("request").click()

while ($ie.Busy -eq $true){Start-Sleep -seconds 2}

$ie.Navigate("https://www.mft1.firstdataclients.com/cgi-bin/messageway/mwi.cgi?    request=ViewDownloaded")

while ($ie.Busy -eq $true){Start-Sleep -seconds 2}


$ie.Document.getElementsByTagName('a')| where-object {$_.href -match "request=TextDownload"} | where-object {$_.href -match 'CL9DFMDE'}| select -First 1 -ExpandProperty 'href'

$link=$ie.Document.getElementsByTagName('a')| where-object {$_.href -match "request=TextDownload"} | where-object {$_.href -match 'CL9DFMDE'}| select -First 1 -ExpandProperty 'href'

$file= $link 

$filename= [string]($file).substring(122)

$filename

$ie.Navigate("$file")

回答1:

I looked all over, and the only way around it was to fake "clicking" on the save button. I did this with the following code:

#------------------------------
#Wait for Download Dialog box to pop up
Sleep 10
while($ie.Busy){Sleep 1} 
#------------------------------

#Hit "S" on the keyboard to hit the "Save" button on the download box
$obj = new-object -com WScript.Shell
$obj.AppActivate('Internet Explorer')
$obj.SendKeys('s')

#------------------------------
#Wait for Download to complete
Sleep 10
while($ie.Busy){Sleep 1} 
#------------------------------


回答2:

You can use Invoke-WebRequest to save documents, like so:

Invoke-WebRequest -Uri "URL_OF_Download_file" -Outfile "save_location"