自动使用Powershell中的IE COM对象从Web保存文件

时间:2015-02-09 02:05:33

标签: internet-explorer powershell com

我在Powershell中使用IE11的COM对象对网站进行身份验证并下拉订单列表。到目前为止,我的脚本已成功发送用户名和密码以及进入订单页面,我甚至可以点击"在下载我需要的文件的链接上。问题是,不是像我需要那样保存文件,而是打开/保存对话框,脚本就会爆炸。

enter image description here

我试图让IE11自动按editing the registry and specifying the Excel.CSV type保存文件,但这不起作用。下载链接实际上是一个调用复杂的Javascript函数的按钮,最后我需要的CSV文件的结果,但是我试图解密发出POST请求的JS并在IE上使用Navigate()方法COM对象无济于事。

我意识到这不是自动化Web流程的最佳方式,但我无法弄清楚如何解决页面上的所有Javascript以使用像Invoke-WebRequest这样的cmdlet。当一切都是Javascript时,有点难以使用HTTP GET和POSTS!

非常感谢任何帮助。这是代码示例。

Function Get-PageElement ($Name,$TagName,$Id) {
    if ($Name) {
        $InternetExplorer.Document.getElementsByName($Name)
    } elseif ($TagName) {
        $InternetExplorer.Document.getElementsByTagName($TagName)
    } elseif ($Id) {
        $InternetExplorer.Document.getElementById($Id)   
    }
}


$script:InternetExplorer = New-Object -com "InternetExplorer.Application"
$script:InternetExplorer.visible = $true
$InternetExplorer.Navigate($Url)


$DownloadButton = Get-PageElement -Id btnExport
$DownloadButton.Click()

2 个答案:

答案 0 :(得分:2)

#Start IE and navigate to your download file/location
$ie = New-Object -Com internetExplorer.Application
$ie.Navigate("http://www.your.website.here.com/awesome_stuff/DOC_1.docx")

#------------------------------
#Wait for Download Dialog box to pop up
Sleep 5
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')

#Hit "Enter" to save the file
$obj.SendKeys('{Enter}')

#Closes IE Downloads window
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{TAB}')
$obj.SendKeys('{Enter}')

答案 1 :(得分:0)

如果您无法解析javascript并获得所需的网址,则可以使用wscript发送关键笔划。请注意,这可能是一个可怕的想法,如果有任何方法解析javascript并获取原始URL以使用WebClient下载,我不会推荐它。

$wsh = new-object -comobject wscript.shell
$id = (Get-Process iexplore* | Where-Object{$_.MainWindowTitle -match "YOUR.WEB.PAGE.TITLE.HERE"}).id
if($wsh.AppActivate($id)){
    start-sleep -milliseconds 500
    $wsh.SendKeys("{S}")
    #I don't have IE11 stuck on 8 due to corporate policy you may need a second sendkeys here
    #if so insert a 500 millisecond delay
}